mysqld.cc 269 KB
Newer Older
Marc Alff's avatar
Marc Alff committed
1
/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
2

unknown's avatar
unknown committed
3 4
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
6

unknown's avatar
unknown committed
7 8 9 10
   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 for more details.
11

unknown's avatar
unknown committed
12 13 14 15
   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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

16
#include "my_global.h"                          /* NO_EMBEDDED_ACCESS_CHECKS */
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
#include "sql_priv.h"
#include "unireg.h"
#include <signal.h>
#ifndef __WIN__
#include <netdb.h>        // getservbyname, servent
#endif
#include "sql_parse.h"    // test_if_data_home_dir
#include "sql_cache.h"    // query_cache, query_cache_*
#include "sql_locale.h"   // MY_LOCALES, my_locales, my_locale_by_name
#include "sql_show.h"     // free_status_vars, add_status_vars,
                          // reset_status_vars
#include "strfunc.h"      // find_set_from_flags
#include "parse_file.h"   // File_parser_dummy_hook
#include "sql_db.h"       // my_database_names_free,
                          // my_database_names_init
#include "sql_table.h"    // release_ddl_log, execute_ddl_log_recovery
#include "sql_connect.h"  // free_max_user_conn, init_max_user_conn,
                          // handle_one_connection
#include "sql_time.h"     // known_date_time_formats,
                          // get_date_time_format_str,
                          // date_time_format_make
#include "tztime.h"       // my_tz_free, my_tz_init, my_tz_SYSTEM
#include "hostname.h"     // hostname_cache_free, hostname_cache_init
#include "sql_acl.h"      // acl_free, grant_free, acl_init,
                          // grant_init
#include "sql_base.h"     // table_def_free, table_def_init,
                          // cached_open_tables,
                          // cached_table_definitions
#include "sql_test.h"     // mysql_print_status
#include "item_create.h"  // item_create_cleanup, item_create_init
#include "sql_servers.h"  // servers_free, servers_init
#include "init.h"         // unireg_init
#include "derror.h"       // init_errmessage
#include "derror.h"       // init_errmessage
#include "des_key_file.h" // load_des_key_file
#include "sql_manager.h"  // stop_handle_manager, start_handle_manager
unknown's avatar
unknown committed
53
#include <m_ctype.h>
54
#include <my_dir.h>
55
#include <my_bit.h>
56
#include "slave.h"
57
#include "rpl_mi.h"
58
#include "sql_repl.h"
unknown's avatar
unknown committed
59
#include "rpl_filter.h"
60
#include "repl_failsafe.h"
61
#include <my_stacktrace.h>
62
#include "mysqld_suffix.h"
unknown's avatar
Merge  
unknown committed
63
#include "mysys_err.h"
64
#include "events.h"
65
#include "sql_audit.h"
66
#include "probes_mysql.h"
67
#include "debug_sync.h"
68

Marc Alff's avatar
Marc Alff committed
69 70 71 72
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
#include "../storage/perfschema/pfs_server.h"
#endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */

73
#include "keycaches.h"
74
#include "../storage/myisam/ha_myisam.h"
75
#include "set_var.h"
76

77 78
#include "rpl_injector.h"

He Zhenxing's avatar
He Zhenxing committed
79 80
#include "rpl_handler.h"

81 82
#ifdef HAVE_SYS_PRCTL_H
#include <sys/prctl.h>
83 84
#endif

unknown's avatar
unknown committed
85 86
#include <thr_alarm.h>
#include <ft_global.h>
87
#include <errmsg.h>
unknown's avatar
Merge  
unknown committed
88 89
#include "sp_rcontext.h"
#include "sp_cache.h"
unknown's avatar
unknown committed
90

91 92
#ifdef HAVE_POLL_H
#include <poll.h>
93 94
#endif

unknown's avatar
unknown committed
95
#define mysqld_charset &my_charset_latin1
96

97
/* stack traces are only supported on linux intel */
98 99 100 101 102 103
#if defined(__linux__)  && defined(__i386__) && defined(USE_PSTACK)
#define	HAVE_STACK_TRACE_ON_SEGV
#include "../pstack/pstack.h"
char pstack_file_name[80];
#endif /* __linux__ */

104 105 106
/* We have HAVE_purify below as this speeds up the shutdown of MySQL */

#if defined(HAVE_DEC_3_2_THREADS) || defined(SIGNALS_DONT_BREAK_READ) || defined(HAVE_purify) && defined(__linux__)
unknown's avatar
unknown committed
107
#define HAVE_CLOSE_SERVER_SOCK 1
108
#endif
unknown's avatar
unknown committed
109

unknown's avatar
unknown committed
110 111 112 113
extern "C" {					// Because of SCO 3.2V4.2
#include <errno.h>
#include <sys/stat.h>
#ifndef __GNU_LIBRARY__
114
#define __GNU_LIBRARY__				// Skip warnings in getopt.h
unknown's avatar
unknown committed
115
#endif
116
#include <my_getopt.h>
unknown's avatar
unknown committed
117 118 119 120 121 122 123 124 125
#ifdef HAVE_SYSENT_H
#include <sysent.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>				// For getpwent
#endif
#ifdef HAVE_GRP_H
#include <grp.h>
#endif
unknown's avatar
Merge  
unknown committed
126
#include <my_net.h>
unknown's avatar
unknown committed
127

128
#if !defined(__WIN__)
unknown's avatar
unknown committed
129
#  ifndef __NETWARE__
unknown's avatar
unknown committed
130
#include <sys/resource.h>
unknown's avatar
unknown committed
131
#  endif /* __NETWARE__ */
unknown's avatar
unknown committed
132 133 134 135 136 137 138 139 140 141
#ifdef HAVE_SYS_UN_H
#  include <sys/un.h>
#endif
#ifdef HAVE_SELECT_H
#  include <select.h>
#endif
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#include <sys/utsname.h>
unknown's avatar
unknown committed
142
#endif /* __WIN__ */
unknown's avatar
unknown committed
143

144
#include <my_libwrap.h>
unknown's avatar
unknown committed
145

146 147 148 149
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif

150 151 152 153 154 155 156
#ifdef __WIN__ 
#include <crtdbg.h>
#define SIGNAL_FMT "exception 0x%x"
#else
#define SIGNAL_FMT "signal %d"
#endif

157 158 159 160 161 162 163 164 165 166
#ifdef HAVE_SOLARIS_LARGE_PAGES
#include <sys/mman.h>
#if defined(__sun__) && defined(__GNUC__) && defined(__cplusplus) \
    && defined(_XOPEN_SOURCE)
extern int getpagesizes(size_t *, int);
extern int getpagesizes2(size_t *, int);
extern int memcntl(caddr_t, size_t, int, caddr_t, int, int);
#endif /* __sun__ ... */
#endif /* HAVE_SOLARIS_LARGE_PAGES */

unknown's avatar
Merge  
unknown committed
167
#ifdef __NETWARE__
unknown's avatar
unknown committed
168 169 170 171
#define zVOLSTATE_ACTIVE 6
#define zVOLSTATE_DEACTIVE 2
#define zVOLSTATE_MAINTENANCE 3

unknown's avatar
unknown committed
172 173 174 175 176 177 178
#undef __event_h__
#include <../include/event.h>
/*
  This #undef exists here because both libc of NetWare and MySQL have
  files named event.h which causes compilation errors.
*/

179
#include <nks/netware.h>
unknown's avatar
unknown committed
180 181 182
#include <nks/vm.h>
#include <library.h>
#include <monitor.h>
unknown's avatar
unknown committed
183 184 185 186 187 188
#include <zOmni.h>                              //For NEB
#include <neb.h>                                //For NEB
#include <nebpub.h>                             //For NEB
#include <zEvent.h>                             //For NSS event structures
#include <zPublics.h>

189 190 191
static void *neb_consumer_id= NULL;             //For storing NEB consumer id
static char datavolname[256]= {0};
static VolumeID_t datavolid;
unknown's avatar
unknown committed
192 193
static event_handle_t eh;
static Report_t ref;
194
static void *refneb= NULL;
195
my_bool event_flag= FALSE;
196
static int volumeid= -1;
unknown's avatar
unknown committed
197 198 199

  /* NEB event callback */
unsigned long neb_event_callback(struct EventBlock *eblock);
200 201 202
static void registerwithneb();
static void getvolumename();
static void getvolumeID(BYTE *volumeName);
unknown's avatar
unknown committed
203
#endif /* __NETWARE__ */
204

unknown's avatar
unknown committed
205

unknown's avatar
unknown committed
206
#ifdef _AIX41
unknown's avatar
unknown committed
207
int initgroups(const char *,unsigned int);
unknown's avatar
unknown committed
208 209
#endif

unknown's avatar
unknown committed
210 211 212 213 214
#if defined(__FreeBSD__) && defined(HAVE_IEEEFP_H)
#include <ieeefp.h>
#ifdef HAVE_FP_EXCEPT				// Fix type conflict
typedef fp_except fp_except_t;
#endif
215 216 217 218 219
#endif /* __FreeBSD__ && HAVE_IEEEFP_H */
#ifdef HAVE_SYS_FPU_H
/* for IRIX to use set_fpc_csr() */
#include <sys/fpu.h>
#endif
220 221 222
#ifdef HAVE_FPU_CONTROL_H
#include <fpu_control.h>
#endif
223 224 225 226
#if defined(__i386__) && !defined(HAVE_FPU_CONTROL_H)
# define fpu_control_t unsigned int
# define _FPU_EXTENDED 0x300
# define _FPU_DOUBLE 0x200
227 228 229
# if defined(__GNUC__) || defined(__SUNPRO_CC)
#  define _FPU_GETCW(cw) asm volatile ("fnstcw %0" : "=m" (*&cw))
#  define _FPU_SETCW(cw) asm volatile ("fldcw %0" : : "m" (*&cw))
230 231 232 233 234
# else
#  define _FPU_GETCW(cw) (cw= 0)
#  define _FPU_SETCW(cw)
# endif
#endif
unknown's avatar
unknown committed
235

236
inline void setup_fpu()
unknown's avatar
unknown committed
237
{
238
#if defined(__FreeBSD__) && defined(HAVE_IEEEFP_H)
unknown's avatar
unknown committed
239
  /* We can't handle floating point exceptions with threads, so disable
unknown's avatar
unknown committed
240
     this on freebsd
241
     Don't fall for overflow, underflow,divide-by-zero or loss of precision
unknown's avatar
unknown committed
242
  */
unknown's avatar
unknown committed
243 244 245
#if defined(__i386__)
  fpsetmask(~(FP_X_INV | FP_X_DNML | FP_X_OFL | FP_X_UFL | FP_X_DZ |
	      FP_X_IMP));
unknown's avatar
unknown committed
246
#else
247 248 249 250
  fpsetmask(~(FP_X_INV |             FP_X_OFL | FP_X_UFL | FP_X_DZ |
              FP_X_IMP));
#endif /* __i386__ */
#endif /* __FreeBSD__ && HAVE_IEEEFP_H */
251

252 253 254 255
#ifdef HAVE_FESETROUND
    /* Set FPU rounding mode to "round-to-nearest" */
  fesetround(FE_TONEAREST);
#endif /* HAVE_FESETROUND */
256 257

  /*
258 259 260 261
    x86 (32-bit) requires FPU precision to be explicitly set to 64 bit
    (double precision) for portable results of floating point operations.
    However, there is no need to do so if compiler is using SSE2 for floating
    point, double values will be stored and processed in 64 bits anyway.
262
  */
263
#if defined(__i386__) && !defined(__SSE2_MATH__)
264 265 266 267 268 269 270 271 272 273 274 275
#if defined(_WIN32)
#if !defined(_WIN64)
  _control87(_PC_53, MCW_PC);
#endif /* !_WIN64 */
#else /* !_WIN32 */
  fpu_control_t cw;
  _FPU_GETCW(cw);
  cw= (cw & ~_FPU_EXTENDED) | _FPU_DOUBLE;
  _FPU_SETCW(cw);
#endif /* _WIN32 && */
#endif /* __i386__ */

276
#if defined(__sgi) && defined(HAVE_SYS_FPU_H)
277
  /* Enable denormalized DOUBLE values support for IRIX */
278 279 280 281 282
  union fpc_csr n;
  n.fc_word = get_fpc_csr();
  n.fc_struct.flush = 0;
  set_fpc_csr(n.fc_word);
#endif
283
}
unknown's avatar
unknown committed
284

unknown's avatar
unknown committed
285 286
} /* cplusplus */

unknown's avatar
unknown committed
287
#define MYSQL_KILL_SIGNAL SIGTERM
unknown's avatar
unknown committed
288 289 290 291 292 293 294 295 296 297 298

#ifdef HAVE_GLIBC2_STYLE_GETHOSTBYNAME_R
#include <sys/types.h>
#else
#include <my_pthread.h>			// For thr_setconcurency()
#endif

#ifdef SOLARIS
extern "C" int gethostname(char *name, int namelen);
#endif

299
extern "C" sig_handler handle_segfault(int sig);
300

301 302 303
#if defined(__linux__)
#define ENABLE_TEMP_POOL 1
#else
Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
304
#define ENABLE_TEMP_POOL 0
305 306
#endif

unknown's avatar
unknown committed
307
/* Constants */
308

unknown's avatar
unknown committed
309
const char *show_comp_option_name[]= {"YES", "NO", "DISABLED"};
310

unknown's avatar
unknown committed
311 312 313 314 315 316 317 318 319
static const char *tc_heuristic_recover_names[]=
{
  "COMMIT", "ROLLBACK", NullS
};
static TYPELIB tc_heuristic_recover_typelib=
{
  array_elements(tc_heuristic_recover_names)-1,"",
  tc_heuristic_recover_names, NULL
};
unknown's avatar
unknown committed
320

unknown's avatar
unknown committed
321
const char *first_keyword= "first", *binary_keyword= "BINARY";
unknown's avatar
unknown committed
322
const char *my_localhost= "localhost", *delayed_user= "DELAYED";
323

unknown's avatar
unknown committed
324
bool opt_large_files= sizeof(my_off_t) > 4;
325 326 327 328

/*
  Used with --help for detailed option
*/
329
static my_bool opt_help= 0, opt_verbose= 0;
330

unknown's avatar
Merge  
unknown committed
331
arg_cmp_func Arg_comparator::comparator_matrix[5][2] =
332 333 334
{{&Arg_comparator::compare_string,     &Arg_comparator::compare_e_string},
 {&Arg_comparator::compare_real,       &Arg_comparator::compare_e_real},
 {&Arg_comparator::compare_int_signed, &Arg_comparator::compare_e_int},
unknown's avatar
Merge  
unknown committed
335 336
 {&Arg_comparator::compare_row,        &Arg_comparator::compare_e_row},
 {&Arg_comparator::compare_decimal,    &Arg_comparator::compare_e_decimal}};
unknown's avatar
unknown committed
337

338 339
const char *log_output_names[] = { "NONE", "FILE", "TABLE", NullS};
static const unsigned int log_output_names_len[]= { 4, 4, 5, 0 };
340
TYPELIB log_output_typelib= {array_elements(log_output_names)-1,"",
341 342
                             log_output_names, 
                             (unsigned int *) log_output_names_len};
343

unknown's avatar
unknown committed
344 345
/* static variables */

Marc Alff's avatar
Marc Alff committed
346 347 348
#ifdef HAVE_PSI_INTERFACE
#if (defined(_WIN32) || defined(HAVE_SMEM)) && !defined(EMBEDDED_LIBRARY)
static PSI_thread_key key_thread_handle_con_namedpipes;
Marc Alff's avatar
Marc Alff committed
349
static PSI_cond_key key_COND_handler_count;
Marc Alff's avatar
Marc Alff committed
350 351 352 353 354 355 356 357 358 359 360 361 362
#endif /* _WIN32 || HAVE_SMEM && !EMBEDDED_LIBRARY */

#if defined(HAVE_SMEM) && !defined(EMBEDDED_LIBRARY)
static PSI_thread_key key_thread_handle_con_sharedmem;
#endif /* HAVE_SMEM && !EMBEDDED_LIBRARY */

#if (defined(_WIN32) || defined(HAVE_SMEM)) && !defined(EMBEDDED_LIBRARY)
static PSI_thread_key key_thread_handle_con_sockets;
#endif /* _WIN32 || HAVE_SMEM && !EMBEDDED_LIBRARY */

#ifdef __WIN__
static PSI_thread_key key_thread_handle_shutdown;
#endif /* __WIN__ */
363 364 365 366

#if defined (HAVE_OPENSSL) && !defined(HAVE_YASSL)
static PSI_rwlock_key key_rwlock_openssl;
#endif
Marc Alff's avatar
Marc Alff committed
367 368
#endif /* HAVE_PSI_INTERFACE */

369
/* the default log output is log tables */
unknown's avatar
unknown committed
370 371 372 373 374 375
static bool lower_case_table_names_used= 0;
static bool volatile select_thread_in_use, signal_thread_in_use;
static bool volatile ready_to_exit;
static my_bool opt_debugging= 0, opt_external_locking= 0, opt_console= 0;
static my_bool opt_short_log_format= 0;
static uint kill_cached_threads, wake_thread;
376
static ulong killed_threads;
unknown's avatar
unknown committed
377 378
static ulong max_used_connections;
static volatile ulong cached_thread_count= 0;
379
static char *mysqld_user, *mysqld_chroot;
unknown's avatar
unknown committed
380
static char *default_character_set_name;
unknown's avatar
unknown committed
381
static char *character_set_filesystem_name;
382
static char *lc_messages;
383
static char *lc_time_names_name;
unknown's avatar
unknown committed
384
static char *my_bind_addr_str;
385 386
static char *default_collation_name;
char *default_storage_engine;
387
static char compiled_default_collation_name[]= MYSQL_DEFAULT_COLLATION_NAME;
unknown's avatar
unknown committed
388
static I_List<THD> thread_cache;
389 390 391
static bool binlog_format_used= false;

LEX_STRING opt_init_connect, opt_init_slave;
unknown's avatar
unknown committed
392

Marc Alff's avatar
Marc Alff committed
393
static mysql_cond_t COND_thread_cache, COND_flush_thread_cache;
unknown's avatar
unknown committed
394

unknown's avatar
unknown committed
395
/* Global variables */
unknown's avatar
unknown committed
396

397
bool opt_bin_log, opt_ignore_builtin_innodb= 0;
398
my_bool opt_log, opt_slow_log;
399
ulonglong log_output_options;
400
my_bool opt_log_queries_not_using_indexes= 0;
401
bool opt_error_log= IF_WIN(1,0);
unknown's avatar
unknown committed
402
bool opt_disable_networking=0, opt_skip_show_db=0;
403
bool opt_skip_name_resolve=0;
404
my_bool opt_character_set_client_handshake= 1;
unknown's avatar
unknown committed
405
bool server_id_supplied = 0;
406
bool opt_endinfo, using_udf_functions;
407
my_bool locked_in_memory;
408
bool opt_using_transactions;
unknown's avatar
unknown committed
409
bool volatile abort_loop;
410
bool volatile shutdown_in_progress;
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
/*
  True if the bootstrap thread is running. Protected by LOCK_thread_count,
  just like thread_count.
  Used in bootstrap() function to determine if the bootstrap thread
  has completed. Note, that we can't use 'thread_count' instead,
  since in 5.1, in presence of the Event Scheduler, there may be
  event threads running in parallel, so it's impossible to know
  what value of 'thread_count' is a sign of completion of the
  bootstrap thread.

  At the same time, we can't start the event scheduler after
  bootstrap either, since we want to be able to process event-related
  SQL commands in the init file and in --bootstrap mode.
*/
bool in_bootstrap= FALSE;
426 427 428 429 430 431 432 433
/**
   @brief 'grant_option' is used to indicate if privileges needs
   to be checked, in which case the lock, LOCK_grant, is used
   to protect access to the grant table.
   @note This flag is dropped in 5.1 
   @see grant_init()
 */
bool volatile grant_option;
unknown's avatar
unknown committed
434

unknown's avatar
unknown committed
435
my_bool opt_skip_slave_start = 0; ///< If set, slave is not autostarted
unknown's avatar
unknown committed
436
my_bool opt_reckless_slave = 0;
unknown's avatar
unknown committed
437 438
my_bool opt_enable_named_pipe= 0;
my_bool opt_local_infile, opt_slave_compressed_protocol;
439 440
my_bool opt_safe_user_create = 0, opt_no_mix_types = 0;
my_bool opt_show_slave_auth_info, opt_sql_bin_update = 0;
441
my_bool opt_log_slave_updates= 0;
442 443 444 445 446 447 448
char *opt_slave_skip_errors;

/**
  compatibility option:
    - index usage hints (USE INDEX without a FOR clause) behave as in 5.0
*/
my_bool old_mode;
449 450 451 452 453 454

/*
  Legacy global handlerton. These will be removed (please do not add more).
*/
handlerton *heap_hton;
handlerton *myisam_hton;
455
handlerton *partition_hton;
456

457
my_bool opt_readonly= 0, use_temp_pool, relay_log_purge;
458
my_bool relay_log_recovery;
unknown's avatar
unknown committed
459
my_bool opt_sync_frm, opt_allow_suspicious_udfs;
460
my_bool opt_secure_auth= 0;
461
char* opt_secure_file_priv;
462
my_bool opt_log_slow_admin_statements= 0;
463
my_bool opt_log_slow_slave_statements= 0;
unknown's avatar
unknown committed
464
my_bool lower_case_file_system= 0;
465
my_bool opt_large_pages= 0;
466
my_bool opt_super_large_pages= 0;
unknown's avatar
unknown committed
467
my_bool opt_myisam_use_mmap= 0;
468
uint   opt_large_page_size= 0;
469 470 471
#if defined(ENABLED_DEBUG_SYNC)
uint    opt_debug_sync_timeout= 0;
#endif /* defined(ENABLED_DEBUG_SYNC) */
472
my_bool opt_old_style_user_limits= 0, trust_function_creators= 0;
unknown's avatar
Merge  
unknown committed
473 474 475 476 477
/*
  True if there is at least one per-hour limit for some user, so we should
  check them before each query (and possibly reset counters when hour is
  changed). False otherwise.
*/
unknown's avatar
unknown committed
478
volatile bool mqh_used = 0;
479
my_bool opt_noacl;
unknown's avatar
Merge  
unknown committed
480
my_bool sp_automatic_privileges= 1;
481

482
ulong opt_binlog_rows_event_max_size;
unknown's avatar
unknown committed
483
const char *binlog_format_names[]= {"MIXED", "STATEMENT", "ROW", NullS};
484
TYPELIB binlog_format_typelib=
485
  { array_elements(binlog_format_names) - 1, "",
486
    binlog_format_names, NULL };
487
#ifdef HAVE_INITGROUPS
unknown's avatar
unknown committed
488
static bool calling_initgroups= FALSE; /**< Used in SIGSEGV handler. */
489
#endif
490
uint mysqld_port, test_flags, select_errors, dropping_tables, ha_open_options;
491
uint mysqld_port_timeout;
492 493
uint delay_key_write_options;
uint protocol_version;
unknown's avatar
unknown committed
494
uint lower_case_table_names;
unknown's avatar
Merge  
unknown committed
495
uint tc_heuristic_recover= 0;
496
uint volatile thread_count;
497
int32 thread_running;
498
ulong thread_created;
499
ulong back_log, connect_timeout, concurrency, server_id;
unknown's avatar
unknown committed
500
ulong table_cache_size, table_def_size;
501
ulong what_to_log;
unknown's avatar
unknown committed
502
ulong query_buff_size, slow_launch_time, slave_open_temp_tables;
unknown's avatar
unknown committed
503
ulong open_files_limit, max_binlog_size, max_relay_log_size;
504 505
ulong slave_trans_retries;
uint  slave_net_timeout;
506
uint slave_exec_mode_options;
unknown's avatar
unknown committed
507
ulonglong slave_type_conversions_options;
unknown's avatar
unknown committed
508
ulong thread_cache_size=0, thread_pool_size= 0;
509 510
ulong binlog_cache_size=0;
ulonglong  max_binlog_cache_size=0;
511
ulong query_cache_size=0;
512
ulong refresh_version;  /* Increments on each reload */
513
query_id_t global_query_id;
514
my_atomic_rwlock_t global_query_id_lock;
515
my_atomic_rwlock_t thread_running_lock;
unknown's avatar
unknown committed
516
ulong aborted_threads, aborted_connects;
unknown's avatar
unknown committed
517 518
ulong delayed_insert_timeout, delayed_insert_limit, delayed_queue_size;
ulong delayed_insert_threads, delayed_insert_writes, delayed_rows_in_use;
unknown's avatar
unknown committed
519
ulong delayed_insert_errors,flush_time;
unknown's avatar
Merge  
unknown committed
520
ulong specialflag=0;
521
ulong binlog_cache_use= 0, binlog_cache_disk_use= 0;
unknown's avatar
unknown committed
522
ulong max_connections, max_connect_errors;
unknown's avatar
unknown committed
523
/**
524 525 526 527
  Limit of the total number of prepared statements in the server.
  Is necessary to protect the server against out-of-memory attacks.
*/
ulong max_prepared_stmt_count;
unknown's avatar
unknown committed
528
/**
529 530 531 532 533 534 535 536 537 538
  Current total number of prepared statements in the server. This number
  is exact, and therefore may not be equal to the difference between
  `com_stmt_prepare' and `com_stmt_close' (global status variables), as
  the latter ones account for all registered attempts to prepare
  a statement (including unsuccessful ones).  Prepared statements are
  currently connection-local: if the same SQL query text is prepared in
  two different connections, this counts as two distinct prepared
  statements.
*/
ulong prepared_stmt_count=0;
unknown's avatar
unknown committed
539
ulong thread_id=1L,current_pid;
540
ulong slow_launch_threads = 0;
541 542
uint sync_binlog_period= 0, sync_relaylog_period= 0,
     sync_relayloginfo_period= 0, sync_masterinfo_period= 0;
unknown's avatar
unknown committed
543
ulong expire_logs_days = 0;
unknown's avatar
unknown committed
544 545
ulong rpl_recovery_rank=0;

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
const double log_10[] = {
  1e000, 1e001, 1e002, 1e003, 1e004, 1e005, 1e006, 1e007, 1e008, 1e009,
  1e010, 1e011, 1e012, 1e013, 1e014, 1e015, 1e016, 1e017, 1e018, 1e019,
  1e020, 1e021, 1e022, 1e023, 1e024, 1e025, 1e026, 1e027, 1e028, 1e029,
  1e030, 1e031, 1e032, 1e033, 1e034, 1e035, 1e036, 1e037, 1e038, 1e039,
  1e040, 1e041, 1e042, 1e043, 1e044, 1e045, 1e046, 1e047, 1e048, 1e049,
  1e050, 1e051, 1e052, 1e053, 1e054, 1e055, 1e056, 1e057, 1e058, 1e059,
  1e060, 1e061, 1e062, 1e063, 1e064, 1e065, 1e066, 1e067, 1e068, 1e069,
  1e070, 1e071, 1e072, 1e073, 1e074, 1e075, 1e076, 1e077, 1e078, 1e079,
  1e080, 1e081, 1e082, 1e083, 1e084, 1e085, 1e086, 1e087, 1e088, 1e089,
  1e090, 1e091, 1e092, 1e093, 1e094, 1e095, 1e096, 1e097, 1e098, 1e099,
  1e100, 1e101, 1e102, 1e103, 1e104, 1e105, 1e106, 1e107, 1e108, 1e109,
  1e110, 1e111, 1e112, 1e113, 1e114, 1e115, 1e116, 1e117, 1e118, 1e119,
  1e120, 1e121, 1e122, 1e123, 1e124, 1e125, 1e126, 1e127, 1e128, 1e129,
  1e130, 1e131, 1e132, 1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139,
  1e140, 1e141, 1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149,
  1e150, 1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159,
  1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168, 1e169,
  1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177, 1e178, 1e179,
  1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186, 1e187, 1e188, 1e189,
  1e190, 1e191, 1e192, 1e193, 1e194, 1e195, 1e196, 1e197, 1e198, 1e199,
  1e200, 1e201, 1e202, 1e203, 1e204, 1e205, 1e206, 1e207, 1e208, 1e209,
  1e210, 1e211, 1e212, 1e213, 1e214, 1e215, 1e216, 1e217, 1e218, 1e219,
  1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229,
  1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239,
  1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249,
  1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259,
  1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267, 1e268, 1e269,
  1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276, 1e277, 1e278, 1e279,
  1e280, 1e281, 1e282, 1e283, 1e284, 1e285, 1e286, 1e287, 1e288, 1e289,
  1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299,
  1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308
};
unknown's avatar
unknown committed
579

580
time_t server_start_time, flush_status_time;
581

582
char mysql_home[FN_REFLEN], pidfile_name[FN_REFLEN], system_time_zone[30];
583
char default_logfile_name[FN_REFLEN];
584
char *default_tz_name;
unknown's avatar
unknown committed
585
char log_error_file[FN_REFLEN], glob_hostname[FN_REFLEN];
unknown's avatar
unknown committed
586
char mysql_real_data_home[FN_REFLEN],
587 588
     lc_messages_dir[FN_REFLEN], reg_ext[FN_EXTLEN],
     mysql_charsets_dir[FN_REFLEN],
589 590
     *opt_init_file, *opt_tc_log_file;
char *lc_messages_dir_ptr, *log_error_file_ptr;
591
char err_shared_dir[FN_REFLEN];
592
char mysql_unpacked_real_data_home[FN_REFLEN];
593
int mysql_unpacked_real_data_home_len;
594
uint mysql_real_data_home_len, mysql_data_home_len= 1;
595
uint reg_ext_length;
596 597 598
const key_map key_map_empty(0);
key_map key_map_full(0);                        // Will be initialized later

599 600
DATE_TIME_FORMAT global_date_format, global_datetime_format, global_time_format;
Time_zone *default_tz;
601

602 603
char *mysql_data_home= const_cast<char*>(".");
const char *mysql_real_data_home_ptr= mysql_real_data_home;
604
char server_version[SERVER_VERSION_LENGTH];
605
char *mysqld_unix_port, *opt_mysql_tmpdir;
606
uint thread_handling;
607

608
/** name of reference on left expression in rewritten IN subquery */
609
const char *in_left_expr_name= "<left expr>";
unknown's avatar
unknown committed
610
/** name of additional condition */
611
const char *in_additional_cond= "<IN COND>";
612 613
const char *in_having_cond= "<IN HAVING>";

unknown's avatar
Merge  
unknown committed
614
my_decimal decimal_zero;
unknown's avatar
unknown committed
615 616 617 618 619 620 621 622
/* classes for comparation parsing/processing */
Eq_creator eq_creator;
Ne_creator ne_creator;
Gt_creator gt_creator;
Lt_creator lt_creator;
Ge_creator ge_creator;
Le_creator le_creator;

Marc Alff's avatar
Marc Alff committed
623
MYSQL_FILE *bootstrap_file;
unknown's avatar
Merge  
unknown committed
624
int bootstrap_error;
625
FILE *stderror_file=0;
unknown's avatar
unknown committed
626

unknown's avatar
unknown committed
627
I_List<THD> threads;
unknown's avatar
unknown committed
628 629
Rpl_filter* rpl_filter;
Rpl_filter* binlog_filter;
unknown's avatar
unknown committed
630

unknown's avatar
unknown committed
631 632
struct system_variables global_system_variables;
struct system_variables max_system_variables;
unknown's avatar
Merge  
unknown committed
633
struct system_status_var global_status_var;
unknown's avatar
unknown committed
634

unknown's avatar
unknown committed
635
MY_TMPDIR mysql_tmpdir_list;
636
MY_BITMAP temp_pool;
unknown's avatar
unknown committed
637

638 639
CHARSET_INFO *system_charset_info, *files_charset_info ;
CHARSET_INFO *national_charset_info, *table_alias_charset;
unknown's avatar
unknown committed
640
CHARSET_INFO *character_set_filesystem;
Marc Alff's avatar
Marc Alff committed
641
CHARSET_INFO *error_message_charset_info;
642

643
MY_LOCALE *my_default_lc_messages;
644 645
MY_LOCALE *my_default_lc_time_names;

646
SHOW_COMP_OPTION have_ssl, have_symlink, have_dlopen, have_query_cache;
647
SHOW_COMP_OPTION have_geometry, have_rtree_keys;
unknown's avatar
unknown committed
648
SHOW_COMP_OPTION have_crypt, have_compress;
649
SHOW_COMP_OPTION have_profiling;
unknown's avatar
unknown committed
650 651

/* Thread specific variables */
652

unknown's avatar
unknown committed
653
pthread_key(MEM_ROOT**,THR_MALLOC);
unknown's avatar
unknown committed
654
pthread_key(THD*, THR_THD);
Marc Alff's avatar
Marc Alff committed
655
mysql_mutex_t LOCK_thread_count;
Marc Alff's avatar
Marc Alff committed
656 657 658 659 660 661 662 663
mysql_mutex_t LOCK_mysql_create_db, LOCK_open,
  LOCK_mapped_file, LOCK_status, LOCK_global_read_lock,
  LOCK_error_log, LOCK_uuid_generator,
  LOCK_delayed_insert, LOCK_delayed_status, LOCK_delayed_create,
  LOCK_crypt,
  LOCK_global_system_variables,
  LOCK_user_conn, LOCK_slave_list, LOCK_active_mi,
  LOCK_connection_count, LOCK_error_messages;
unknown's avatar
unknown committed
664
/**
665 666 667 668 669 670
  The below lock protects access to two global server variables:
  max_prepared_stmt_count and prepared_stmt_count. These variables
  set the limit and hold the current total number of prepared statements
  in the server, respectively. As PREPARE/DEALLOCATE rate in a loaded
  server may be fairly high, we need a dedicated lock.
*/
Marc Alff's avatar
Marc Alff committed
671
mysql_mutex_t LOCK_prepared_stmt_count;
672
#ifdef HAVE_OPENSSL
Marc Alff's avatar
Marc Alff committed
673
mysql_mutex_t LOCK_des_key_file;
674
#endif
Marc Alff's avatar
Marc Alff committed
675 676
mysql_rwlock_t LOCK_grant, LOCK_sys_init_connect, LOCK_sys_init_slave;
mysql_rwlock_t LOCK_system_variables_hash;
Marc Alff's avatar
Marc Alff committed
677
mysql_cond_t COND_thread_count;
Marc Alff's avatar
Marc Alff committed
678
mysql_cond_t COND_refresh, COND_global_read_lock;
unknown's avatar
unknown committed
679 680
pthread_t signal_thread;
pthread_attr_t connection_attrib;
Marc Alff's avatar
Marc Alff committed
681 682
mysql_mutex_t LOCK_server_started;
mysql_cond_t COND_server_started;
unknown's avatar
unknown committed
683 684

int mysqld_server_started= 0;
unknown's avatar
unknown committed
685

686 687
File_parser_dummy_hook file_parser_dummy_hook;

unknown's avatar
unknown committed
688 689 690
/* replication parameters, if master_host is not NULL, we are a slave */
uint report_port= MYSQL_PORT;
ulong master_retry_count=0;
691
char *master_info_file;
unknown's avatar
unknown committed
692
char *relay_log_info_file, *report_user, *report_password, *report_host;
unknown's avatar
unknown committed
693
char *opt_relay_logname = 0, *opt_relaylog_index_name=0;
694
char *opt_logname, *opt_slow_logname;
unknown's avatar
unknown committed
695 696 697 698

/* Static variables */

static bool kill_in_progress, segfaulted;
699 700 701 702
#ifdef HAVE_STACK_TRACE_ON_SEGV
static my_bool opt_do_pstack;
#endif /* HAVE_STACK_TRACE_ON_SEGV */
static my_bool opt_bootstrap, opt_myisam_log;
unknown's avatar
unknown committed
703
static int cleanup_done;
704
static ulong opt_specialflag;
705
static char *opt_update_logname, *opt_binlog_index_name;
706
char *mysql_home_ptr, *pidfile_name_ptr;
Marc Alff's avatar
Marc Alff committed
707
/** Initial command line arguments (count), after load_defaults().*/
unknown's avatar
unknown committed
708
static int defaults_argc;
Marc Alff's avatar
Marc Alff committed
709 710 711 712 713 714 715 716
/**
  Initial command line arguments (arguments), after load_defaults().
  This memory is allocated by @c load_defaults() and should be freed
  using @c free_defaults().
  Do not modify defaults_argc / defaults_argv,
  use remaining_argc / remaining_argv instead to parse the command
  line arguments in multiple steps.
*/
unknown's avatar
unknown committed
717
static char **defaults_argv;
Marc Alff's avatar
Marc Alff committed
718 719 720 721
/** Remaining command line arguments (count), filtered by handle_options().*/
static int remaining_argc;
/** Remaining command line arguments (arguments), filtered by handle_options().*/
static char **remaining_argv;
unknown's avatar
unknown committed
722 723
static char *opt_bin_logname;

724 725 726
int orig_argc;
char **orig_argv;

Marc Alff's avatar
Marc Alff committed
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
/*
  Since buffered_option_error_reporter is only used currently
  for parsing performance schema options, this code is not needed
  when the performance schema is not compiled in.
*/
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
/**
  A log message for the error log, buffered in memory.
  Log messages are temporarily buffered when generated before the error log
  is initialized, and then printed once the error log is ready.
*/
class Buffered_log : public Sql_alloc
{
public:
  Buffered_log(enum loglevel level, const char *message);

  ~Buffered_log()
  {}

  void print(void);

private:
  /** Log message level. */
  enum loglevel m_level;
  /** Log message text. */
  String m_message;
};

/**
  Constructor.
  @param level          the message log level
  @param message        the message text
*/
Buffered_log::Buffered_log(enum loglevel level, const char *message)
  : m_level(level), m_message()
{
  m_message.copy(message, strlen(message), &my_charset_latin1);
}

/**
  Print a buffered log to the real log file.
*/
void Buffered_log::print()
{
  /*
    Since messages are buffered, they can be printed out
    of order with other entries in the log.
    Add "Buffered xxx" to the message text to prevent confusion.
  */
  switch(m_level)
  {
  case ERROR_LEVEL:
    sql_print_error("Buffered error: %s\n", m_message.c_ptr_safe());
    break;
  case WARNING_LEVEL:
    sql_print_warning("Buffered warning: %s\n", m_message.c_ptr_safe());
    break;
  case INFORMATION_LEVEL:
    sql_print_information("Buffered information: %s\n", m_message.c_ptr_safe());
    break;
  }
}

/**
  Collection of all the buffered log messages.
*/
class Buffered_logs
{
public:
  Buffered_logs()
  {}

  ~Buffered_logs()
  {}

  void init();
  void cleanup();

  void buffer(enum loglevel m_level, const char *msg);
  void print();
private:
  /**
    Memory root to use to store buffered logs.
    This memory root lifespan is between init and cleanup.
    Once the buffered logs are printed, they are not needed anymore,
    and all the memory used is reclaimed.
  */
  MEM_ROOT m_root;
  /** List of buffered log messages. */
  List<Buffered_log> m_list;
};

void Buffered_logs::init()
{
  init_alloc_root(&m_root, 1024, 0);
}

void Buffered_logs::cleanup()
{
  m_list.delete_elements();
  free_root(&m_root, MYF(0));
}

/**
  Add a log message to the buffer.
*/
void Buffered_logs::buffer(enum loglevel level, const char *msg)
{
  /*
    Do not let Sql_alloc::operator new(size_t) allocate memory,
    there is no memory root associated with the main() thread.
    Give explicitly the proper memory root to use to
    Sql_alloc::operator new(size_t, MEM_ROOT *) instead.
  */
  Buffered_log *log= new (&m_root) Buffered_log(level, msg);
  if (log)
    m_list.push_back(log, &m_root);
}

/**
  Print buffered log messages.
*/
void Buffered_logs::print()
{
  Buffered_log *log;
  List_iterator_fast<Buffered_log> it(m_list);
  while ((log= it++))
    log->print();
}

/** Logs reported before a logger is available. */
static Buffered_logs buffered_logs;

860
#ifndef EMBEDDED_LIBRARY
Marc Alff's avatar
Marc Alff committed
861 862 863 864 865
/**
  Error reporter that buffer log messages.
  @param level          log message level
  @param format         log message format string
*/
866 867 868
C_MODE_START
static void buffered_option_error_reporter(enum loglevel level,
                                           const char *format, ...)
Marc Alff's avatar
Marc Alff committed
869 870 871 872 873 874 875 876 877
{
  va_list args;
  char buffer[1024];

  va_start(args, format);
  my_vsnprintf(buffer, sizeof(buffer), format, args);
  va_end(args);
  buffered_logs.buffer(level, buffer);
}
878 879
C_MODE_END
#endif /* !EMBEDDED_LIBRARY */
Marc Alff's avatar
Marc Alff committed
880 881
#endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */

unknown's avatar
unknown committed
882
static my_socket unix_sock,ip_sock;
unknown's avatar
unknown committed
883
struct rand_struct sql_rand; ///< used by sql_class.cc:THD::THD()
unknown's avatar
unknown committed
884

unknown's avatar
unknown committed
885 886 887
#ifndef EMBEDDED_LIBRARY
struct passwd *user_info;
static pthread_t select_thread;
unknown's avatar
unknown committed
888
static uint thr_kill_signal;
unknown's avatar
unknown committed
889 890
#endif

unknown's avatar
unknown committed
891 892
/* OS specific variables */

unknown's avatar
unknown committed
893 894 895
#ifdef __WIN__
#undef	 getpid
#include <process.h>
unknown's avatar
unknown committed
896

Marc Alff's avatar
Marc Alff committed
897
static mysql_cond_t COND_handler_count;
unknown's avatar
unknown committed
898 899 900 901 902
static uint handler_count;
static bool start_mode=0, use_opt_args;
static int opt_argc;
static char **opt_argv;

unknown's avatar
unknown committed
903
#if !defined(EMBEDDED_LIBRARY)
unknown's avatar
unknown committed
904
static HANDLE hEventShutdown;
905
static char shutdown_event_name[40];
unknown's avatar
unknown committed
906
#include "nt_servc.h"
unknown's avatar
unknown committed
907
static	 NTService  Service;	      ///< Service object for WinNT
unknown's avatar
unknown committed
908 909 910
#endif /* EMBEDDED_LIBRARY */
#endif /* __WIN__ */

Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
911
#ifdef _WIN32
912
static char pipe_name[512];
unknown's avatar
unknown committed
913 914 915
static SECURITY_ATTRIBUTES saPipeSecurity;
static SECURITY_DESCRIPTOR sdPipeDescriptor;
static HANDLE hPipe = INVALID_HANDLE_VALUE;
unknown's avatar
unknown committed
916
#endif
unknown's avatar
unknown committed
917

unknown's avatar
unknown committed
918
#ifndef EMBEDDED_LIBRARY
919
bool mysqld_embedded=0;
unknown's avatar
unknown committed
920
#else
921
bool mysqld_embedded=1;
unknown's avatar
unknown committed
922 923
#endif

924 925
static my_bool plugins_are_initialized= FALSE;

unknown's avatar
unknown committed
926 927 928 929
#ifndef DBUG_OFF
static const char* default_dbug_option;
#endif
#ifdef HAVE_LIBWRAP
930
const char *libwrapName= NULL;
931 932
int allow_severity = LOG_INFO;
int deny_severity = LOG_WARNING;
unknown's avatar
unknown committed
933 934 935 936 937 938 939
#endif
#ifdef HAVE_QUERY_CACHE
ulong query_cache_min_res_unit= QUERY_CACHE_MIN_RESULT_DATA_SIZE;
Query_cache query_cache;
#endif
#ifdef HAVE_SMEM
char *shared_memory_base_name= default_shared_memory_base_name;
940
my_bool opt_enable_shared_memory;
941
HANDLE smem_event_connect_request= 0;
unknown's avatar
unknown committed
942 943
#endif

unknown's avatar
unknown committed
944 945
scheduler_functions thread_scheduler;

946 947 948 949
my_bool opt_use_ssl  = 0;
char *opt_ssl_ca= NULL, *opt_ssl_capath= NULL, *opt_ssl_cert= NULL,
     *opt_ssl_cipher= NULL, *opt_ssl_key= NULL;

unknown's avatar
unknown committed
950
#ifdef HAVE_OPENSSL
951
#include <openssl/crypto.h>
unknown's avatar
unknown committed
952
#ifndef HAVE_YASSL
953 954
typedef struct CRYPTO_dynlock_value
{
Marc Alff's avatar
Marc Alff committed
955
  mysql_rwlock_t lock;
956 957 958 959 960 961 962 963
} openssl_lock_t;

static openssl_lock_t *openssl_stdlocks;
static openssl_lock_t *openssl_dynlock_create(const char *, int);
static void openssl_dynlock_destroy(openssl_lock_t *, const char *, int);
static void openssl_lock_function(int, int, const char *, int);
static void openssl_lock(int, openssl_lock_t *, const char *, int);
static unsigned long openssl_id_function();
unknown's avatar
unknown committed
964
#endif
unknown's avatar
unknown committed
965
char *des_key_file;
Konstantin Osipov's avatar
Konstantin Osipov committed
966
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
967
struct st_VioSSLFd *ssl_acceptor_fd;
Konstantin Osipov's avatar
Konstantin Osipov committed
968
#endif
unknown's avatar
unknown committed
969 970
#endif /* HAVE_OPENSSL */

971 972 973 974 975
/**
  Number of currently active user connections. The variable is protected by
  LOCK_connection_count.
*/
uint connection_count= 0;
unknown's avatar
unknown committed
976 977 978

/* Function declarations */

979
pthread_handler_t signal_hand(void *arg);
980
static int mysql_init_variables(void);
Marc Alff's avatar
Marc Alff committed
981 982
static int get_options(int *argc_ptr, char ***argv_ptr);
static bool add_terminator(DYNAMIC_ARRAY *options);
983
extern "C" my_bool mysqld_get_one_option(int, const struct my_option *, char *);
984
static void set_server_version(void);
985
static int init_thread_environment();
unknown's avatar
unknown committed
986
static char *get_relative_path(const char *path);
987
static int fix_paths(void);
988 989 990 991
void handle_connections_sockets();
#ifdef _WIN32
pthread_handler_t handle_connections_sockets_thread(void *arg);
#endif
992
pthread_handler_t kill_server_thread(void *arg);
Marc Alff's avatar
Marc Alff committed
993
static void bootstrap(MYSQL_FILE *file);
unknown's avatar
unknown committed
994
static bool read_init_file(char *file_name);
Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
995
#ifdef _WIN32
996
pthread_handler_t handle_connections_namedpipes(void *arg);
unknown's avatar
unknown committed
997
#endif
998
#ifdef HAVE_SMEM
999
pthread_handler_t handle_connections_shared_memory(void *arg);
1000
#endif
1001
pthread_handler_t handle_slave(void *arg);
unknown's avatar
unknown committed
1002
static void clean_up(bool print_message);
1003 1004 1005
static int test_if_case_insensitive(const char *dir_name);

#ifndef EMBEDDED_LIBRARY
1006
static void usage(void);
1007 1008
static void start_signal_handler(void);
static void close_server_sock();
unknown's avatar
unknown committed
1009
static void clean_up_mutexes(void);
1010
static void wait_for_signal_thread_to_end(void);
1011
static void create_pid_file();
1012
static void mysqld_exit(int exit_code) __attribute__((noreturn));
1013
#endif
Konstantin Osipov's avatar
Konstantin Osipov committed
1014
static void end_ssl();
1015

1016 1017

#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
/****************************************************************************
** Code to end mysqld
****************************************************************************/

static void close_connections(void)
{
#ifdef EXTRA_DEBUG
  int count=0;
#endif
  DBUG_ENTER("close_connections");

  /* Clear thread cache */
  kill_cached_threads++;
  flush_thread_cache();

  /* kill connection thread */
1034
#if !defined(__WIN__) && !defined(__NETWARE__)
unknown's avatar
unknown committed
1035 1036
  DBUG_PRINT("quit", ("waiting for select thread: 0x%lx",
                      (ulong) select_thread));
Marc Alff's avatar
Marc Alff committed
1037
  mysql_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
1038 1039 1040 1041 1042 1043

  while (select_thread_in_use)
  {
    struct timespec abstime;
    int error;
    LINT_INIT(error);
unknown's avatar
unknown committed
1044
    DBUG_PRINT("info",("Waiting for select thread"));
1045

unknown's avatar
unknown committed
1046
#ifndef DONT_USE_THR_ALARM
1047
    if (pthread_kill(select_thread, thr_client_alarm))
unknown's avatar
unknown committed
1048 1049
      break;					// allready dead
#endif
1050
    set_timespec(abstime, 2);
1051
    for (uint tmp=0 ; tmp < 10 && select_thread_in_use; tmp++)
unknown's avatar
unknown committed
1052
    {
Marc Alff's avatar
Marc Alff committed
1053 1054
      error= mysql_cond_timedwait(&COND_thread_count, &LOCK_thread_count,
                                  &abstime);
unknown's avatar
unknown committed
1055 1056 1057 1058 1059
      if (error != EINTR)
	break;
    }
#ifdef EXTRA_DEBUG
    if (error != 0 && !count++)
Marc Alff's avatar
Marc Alff committed
1060
      sql_print_error("Got error %d from mysql_cond_timedwait", error);
unknown's avatar
unknown committed
1061
#endif
unknown's avatar
unknown committed
1062
    close_server_sock();
unknown's avatar
unknown committed
1063
  }
Marc Alff's avatar
Marc Alff committed
1064
  mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
1065 1066 1067 1068 1069
#endif /* __WIN__ */


  /* Abort listening to new connections */
  DBUG_PRINT("quit",("Closing sockets"));
unknown's avatar
Merge  
unknown committed
1070
  if (!opt_disable_networking )
unknown's avatar
unknown committed
1071 1072 1073
  {
    if (ip_sock != INVALID_SOCKET)
    {
1074
      (void) shutdown(ip_sock, SHUT_RDWR);
unknown's avatar
unknown committed
1075 1076 1077 1078
      (void) closesocket(ip_sock);
      ip_sock= INVALID_SOCKET;
    }
  }
Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
1079
#ifdef _WIN32
unknown's avatar
unknown committed
1080
  if (hPipe != INVALID_HANDLE_VALUE && opt_enable_named_pipe)
unknown's avatar
unknown committed
1081
  {
unknown's avatar
merge  
unknown committed
1082
    HANDLE temp;
unknown's avatar
Merge  
unknown committed
1083
    DBUG_PRINT("quit", ("Closing named pipes") );
1084

unknown's avatar
merge  
unknown committed
1085
    /* Create connection to the handle named pipe handler to break the loop */
1086
    if ((temp = CreateFile(pipe_name,
unknown's avatar
merge  
unknown committed
1087 1088 1089 1090 1091 1092 1093
			   GENERIC_READ | GENERIC_WRITE,
			   0,
			   NULL,
			   OPEN_EXISTING,
			   0,
			   NULL )) != INVALID_HANDLE_VALUE)
    {
1094
      WaitNamedPipe(pipe_name, 1000);
unknown's avatar
merge  
unknown committed
1095 1096 1097 1098 1099 1100
      DWORD dwMode = PIPE_READMODE_BYTE | PIPE_WAIT;
      SetNamedPipeHandleState(temp, &dwMode, NULL, NULL);
      CancelIo(temp);
      DisconnectNamedPipe(temp);
      CloseHandle(temp);
    }
unknown's avatar
unknown committed
1101 1102 1103 1104 1105
  }
#endif
#ifdef HAVE_SYS_UN_H
  if (unix_sock != INVALID_SOCKET)
  {
1106
    (void) shutdown(unix_sock, SHUT_RDWR);
unknown's avatar
unknown committed
1107
    (void) closesocket(unix_sock);
1108
    (void) unlink(mysqld_unix_port);
unknown's avatar
unknown committed
1109 1110 1111
    unix_sock= INVALID_SOCKET;
  }
#endif
1112
  end_thr_alarm(0);			 // Abort old alarms.
unknown's avatar
unknown committed
1113

1114 1115 1116 1117 1118
  /*
    First signal all threads that it's time to die
    This will give the threads some time to gracefully abort their
    statements and inform their clients that the server is about to die.
  */
unknown's avatar
unknown committed
1119 1120

  THD *tmp;
Marc Alff's avatar
Marc Alff committed
1121
  mysql_mutex_lock(&LOCK_thread_count); // For unlink from list
unknown's avatar
unknown committed
1122 1123 1124 1125 1126 1127

  I_List_iterator<THD> it(threads);
  while ((tmp=it++))
  {
    DBUG_PRINT("quit",("Informing thread %ld that it's time to die",
		       tmp->thread_id));
1128
    /* We skip slave threads & scheduler on this first loop through. */
1129
    if (tmp->slave_thread)
1130
      continue;
1131

unknown's avatar
unknown committed
1132
    tmp->killed= THD::KILL_CONNECTION;
unknown's avatar
unknown committed
1133
    thread_scheduler.post_kill_notification(tmp);
unknown's avatar
unknown committed
1134 1135 1136
    if (tmp->mysys_var)
    {
      tmp->mysys_var->abort=1;
Marc Alff's avatar
Marc Alff committed
1137
      mysql_mutex_lock(&tmp->mysys_var->mutex);
unknown's avatar
unknown committed
1138
      if (tmp->mysys_var->current_cond)
unknown's avatar
unknown committed
1139
      {
Marc Alff's avatar
Marc Alff committed
1140 1141 1142
        mysql_mutex_lock(tmp->mysys_var->current_mutex);
        mysql_cond_broadcast(tmp->mysys_var->current_cond);
        mysql_mutex_unlock(tmp->mysys_var->current_mutex);
unknown's avatar
unknown committed
1143
      }
Marc Alff's avatar
Marc Alff committed
1144
      mysql_mutex_unlock(&tmp->mysys_var->mutex);
unknown's avatar
unknown committed
1145 1146
    }
  }
Marc Alff's avatar
Marc Alff committed
1147
  mysql_mutex_unlock(&LOCK_thread_count); // For unlink from list
unknown's avatar
unknown committed
1148

1149
  Events::deinit();
1150 1151
  end_slave();

unknown's avatar
unknown committed
1152
  if (thread_count)
1153
    sleep(2);					// Give threads time to die
unknown's avatar
unknown committed
1154

1155 1156 1157 1158 1159
  /*
    Force remaining threads to die by closing the connection to the client
    This will ensure that threads that are waiting for a command from the
    client on a blocking read call are aborted.
  */
unknown's avatar
unknown committed
1160 1161 1162 1163

  for (;;)
  {
    DBUG_PRINT("quit",("Locking LOCK_thread_count"));
Marc Alff's avatar
Marc Alff committed
1164
    mysql_mutex_lock(&LOCK_thread_count); // For unlink from list
unknown's avatar
unknown committed
1165 1166 1167
    if (!(tmp=threads.get()))
    {
      DBUG_PRINT("quit",("Unlocking LOCK_thread_count"));
Marc Alff's avatar
Marc Alff committed
1168
      mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
1169 1170 1171
      break;
    }
#ifndef __bsdi__				// Bug in BSDI kernel
1172
    if (tmp->vio_ok())
unknown's avatar
unknown committed
1173
    {
1174
      if (global_system_variables.log_warnings)
1175
        sql_print_warning(ER_DEFAULT(ER_FORCING_CLOSE),my_progname,
1176
                          tmp->thread_id,
1177 1178
                          (tmp->main_security_ctx.user ?
                           tmp->main_security_ctx.user : ""));
1179
      close_connection(tmp,0,0);
unknown's avatar
unknown committed
1180 1181 1182
    }
#endif
    DBUG_PRINT("quit",("Unlocking LOCK_thread_count"));
Marc Alff's avatar
Marc Alff committed
1183
    mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
1184 1185 1186
  }
  /* All threads has now been aborted */
  DBUG_PRINT("quit",("Waiting for threads to die (count=%u)",thread_count));
Marc Alff's avatar
Marc Alff committed
1187
  mysql_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
1188 1189
  while (thread_count)
  {
Marc Alff's avatar
Marc Alff committed
1190
    mysql_cond_wait(&COND_thread_count, &LOCK_thread_count);
unknown's avatar
unknown committed
1191 1192
    DBUG_PRINT("quit",("One thread died (count=%u)",thread_count));
  }
Marc Alff's avatar
Marc Alff committed
1193
  mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
1194

1195
  close_active_mi();
unknown's avatar
unknown committed
1196 1197 1198 1199
  DBUG_PRINT("quit",("close_connections thread"));
  DBUG_VOID_RETURN;
}

1200

1201
static void close_server_sock()
unknown's avatar
unknown committed
1202
{
1203
#ifdef HAVE_CLOSE_SERVER_SOCK
unknown's avatar
unknown committed
1204
  DBUG_ENTER("close_server_sock");
1205 1206 1207
  my_socket tmp_sock;
  tmp_sock=ip_sock;
  if (tmp_sock != INVALID_SOCKET)
unknown's avatar
unknown committed
1208 1209
  {
    ip_sock=INVALID_SOCKET;
1210
    DBUG_PRINT("info",("calling shutdown on TCP/IP socket"));
Konstantin Osipov's avatar
Konstantin Osipov committed
1211
    (void) shutdown(tmp_sock, SHUT_RDWR);
unknown's avatar
unknown committed
1212
#if defined(__NETWARE__)
1213
    /*
unknown's avatar
unknown committed
1214 1215
      The following code is disabled for normal systems as it causes MySQL
      to hang on AIX 4.3 during shutdown
1216
    */
1217
    DBUG_PRINT("info",("calling closesocket on TCP/IP socket"));
Konstantin Osipov's avatar
Konstantin Osipov committed
1218
    (void) closesocket(tmp_sock);
1219
#endif
unknown's avatar
unknown committed
1220
  }
1221 1222
  tmp_sock=unix_sock;
  if (tmp_sock != INVALID_SOCKET)
unknown's avatar
unknown committed
1223
  {
1224
    unix_sock=INVALID_SOCKET;
1225
    DBUG_PRINT("info",("calling shutdown on unix socket"));
Konstantin Osipov's avatar
Konstantin Osipov committed
1226
    (void) shutdown(tmp_sock, SHUT_RDWR);
unknown's avatar
unknown committed
1227
#if defined(__NETWARE__)
unknown's avatar
unknown committed
1228
    /*
1229 1230
      The following code is disabled for normal systems as it may cause MySQL
      to hang on AIX 4.3 during shutdown
unknown's avatar
unknown committed
1231 1232
    */
    DBUG_PRINT("info",("calling closesocket on unix/IP socket"));
Konstantin Osipov's avatar
Konstantin Osipov committed
1233
    (void) closesocket(tmp_sock);
unknown's avatar
unknown committed
1234
#endif
Konstantin Osipov's avatar
Konstantin Osipov committed
1235
    (void) unlink(mysqld_unix_port);
unknown's avatar
unknown committed
1236 1237 1238
  }
  DBUG_VOID_RETURN;
#endif
1239
}
unknown's avatar
unknown committed
1240

1241 1242
#endif /*EMBEDDED_LIBRARY*/

1243

unknown's avatar
unknown committed
1244 1245 1246 1247
void kill_mysql(void)
{
  DBUG_ENTER("kill_mysql");

1248
#if defined(SIGNALS_DONT_BREAK_READ) && !defined(EMBEDDED_LIBRARY)
1249 1250
  abort_loop=1;					// Break connection loops
  close_server_sock();				// Force accept to wake up
1251
#endif
unknown's avatar
unknown committed
1252

unknown's avatar
unknown committed
1253
#if defined(__WIN__)
unknown's avatar
unknown committed
1254
#if !defined(EMBEDDED_LIBRARY)
unknown's avatar
unknown committed
1255 1256 1257 1258 1259
  {
    if (!SetEvent(hEventShutdown))
    {
      DBUG_PRINT("error",("Got error: %ld from SetEvent",GetLastError()));
    }
1260 1261 1262 1263 1264 1265
    /*
      or:
      HANDLE hEvent=OpenEvent(0, FALSE, "MySqlShutdown");
      SetEvent(hEventShutdown);
      CloseHandle(hEvent);
    */
unknown's avatar
unknown committed
1266
  }
unknown's avatar
unknown committed
1267
#endif
unknown's avatar
unknown committed
1268
#elif defined(HAVE_PTHREAD_KILL)
1269
  if (pthread_kill(signal_thread, MYSQL_KILL_SIGNAL))
unknown's avatar
unknown committed
1270 1271 1272 1273
  {
    DBUG_PRINT("error",("Got error %d from pthread_kill",errno)); /* purecov: inspected */
  }
#elif !defined(SIGNALS_DONT_BREAK_READ)
1274
  kill(current_pid, MYSQL_KILL_SIGNAL);
unknown's avatar
unknown committed
1275
#endif
unknown's avatar
unknown committed
1276 1277 1278
  DBUG_PRINT("quit",("After pthread_kill"));
  shutdown_in_progress=1;			// Safety if kill didn't work
#ifdef SIGNALS_DONT_BREAK_READ
1279
  if (!kill_in_progress)
unknown's avatar
unknown committed
1280 1281
  {
    pthread_t tmp;
unknown's avatar
unknown committed
1282
    abort_loop=1;
Marc Alff's avatar
Marc Alff committed
1283 1284 1285
    if (mysql_thread_create(0, /* Not instrumented */
                            &tmp, &connection_attrib, kill_server_thread,
                            (void*) 0))
1286
      sql_print_error("Can't create thread to kill server");
unknown's avatar
unknown committed
1287
  }
1288
#endif
unknown's avatar
unknown committed
1289
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
1290 1291
}

unknown's avatar
unknown committed
1292 1293
/**
  Force server down. Kill all connections and threads and exit.
1294

unknown's avatar
unknown committed
1295
  @param  sig_ptr       Signal number that caused kill_server to be called.
1296

unknown's avatar
unknown committed
1297
  @note
1298 1299 1300 1301
    A signal number of 0 mean that the function was not called
    from a signal handler and there is thus no signal to block
    or stop, we just want to kill the server.
*/
unknown's avatar
unknown committed
1302

1303
#if defined(__NETWARE__)
unknown's avatar
unknown committed
1304
extern "C" void kill_server(int sig_ptr)
1305
#define RETURN_FROM_KILL_SERVER return
unknown's avatar
unknown committed
1306
#elif !defined(__WIN__)
unknown's avatar
unknown committed
1307
static void *kill_server(void *sig_ptr)
1308
#define RETURN_FROM_KILL_SERVER return 0
unknown's avatar
unknown committed
1309 1310
#else
static void __cdecl kill_server(int sig_ptr)
1311
#define RETURN_FROM_KILL_SERVER return
unknown's avatar
unknown committed
1312 1313 1314
#endif
{
  DBUG_ENTER("kill_server");
1315
#ifndef EMBEDDED_LIBRARY
unknown's avatar
Merge  
unknown committed
1316
  int sig=(int) (long) sig_ptr;			// This is passed a int
1317
  // if there is a signal during the kill in progress, ignore the other
unknown's avatar
unknown committed
1318
  if (kill_in_progress)				// Safety
1319 1320
  {
    DBUG_LEAVE;
unknown's avatar
unknown committed
1321
    RETURN_FROM_KILL_SERVER;
1322
  }
unknown's avatar
unknown committed
1323 1324
  kill_in_progress=TRUE;
  abort_loop=1;					// This should be set
1325
  if (sig != 0) // 0 is not a valid signal number
1326
    my_sigset(sig, SIG_IGN);                    /* purify inspected */
unknown's avatar
unknown committed
1327
  if (sig == MYSQL_KILL_SIGNAL || sig == 0)
1328
    sql_print_information(ER_DEFAULT(ER_NORMAL_SHUTDOWN),my_progname);
unknown's avatar
unknown committed
1329
  else
1330
    sql_print_error(ER_DEFAULT(ER_GOT_SIGNAL),my_progname,sig); /* purecov: inspected */
unknown's avatar
unknown committed
1331

1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
#if defined(HAVE_SMEM) && defined(__WIN__)    
  /*    
   Send event to smem_event_connect_request for aborting    
   */    
  if (!SetEvent(smem_event_connect_request))    
  {      
	  DBUG_PRINT("error",
		("Got error: %ld from SetEvent of smem_event_connect_request",
		 GetLastError()));    
  }
#endif  
  
unknown's avatar
unknown committed
1344
  close_connections();
1345 1346
  if (sig != MYSQL_KILL_SIGNAL &&
      sig != 0)
unknown's avatar
unknown committed
1347 1348
    unireg_abort(1);				/* purecov: inspected */
  else
1349
    unireg_end();
unknown's avatar
Merge  
unknown committed
1350

1351
  /* purecov: begin deadcode */
unknown's avatar
unknown committed
1352
#ifdef __NETWARE__
unknown's avatar
unknown committed
1353
  if (!event_flag)
unknown's avatar
Merge  
unknown committed
1354
    pthread_join(select_thread, NULL);		// wait for main thread
unknown's avatar
unknown committed
1355
#endif /* __NETWARE__ */
1356

1357
  DBUG_LEAVE;                                   // Must match DBUG_ENTER()
1358
  my_thread_end();
1359 1360
  pthread_exit(0);
  /* purecov: end */
unknown's avatar
unknown committed
1361

1362 1363 1364 1365 1366
  RETURN_FROM_KILL_SERVER;                      // Avoid compiler warnings

#else /* EMBEDDED_LIBRARY*/

  DBUG_LEAVE;
unknown's avatar
unknown committed
1367
  RETURN_FROM_KILL_SERVER;
1368 1369

#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
1370 1371 1372
}


unknown's avatar
unknown committed
1373
#if defined(USE_ONE_SIGNAL_HAND) || (defined(__NETWARE__) && defined(SIGNALS_DONT_BREAK_READ))
1374
pthread_handler_t kill_server_thread(void *arg __attribute__((unused)))
unknown's avatar
unknown committed
1375 1376 1377
{
  my_thread_init();				// Initialize new thread
  kill_server(0);
1378 1379 1380
  /* purecov: begin deadcode */
  my_thread_end();
  pthread_exit(0);
unknown's avatar
unknown committed
1381
  return 0;
1382
  /* purecov: end */
unknown's avatar
unknown committed
1383 1384 1385
}
#endif

1386

1387
extern "C" sig_handler print_signal_warning(int sig)
unknown's avatar
unknown committed
1388
{
unknown's avatar
unknown committed
1389
  if (global_system_variables.log_warnings)
1390
    sql_print_warning("Got signal %d from thread %ld", sig,my_thread_id());
1391
#ifdef SIGNAL_HANDLER_RESET_ON_DELIVERY
1392
  my_sigset(sig,print_signal_warning);		/* int. thread system calls */
unknown's avatar
unknown committed
1393
#endif
1394
#if !defined(__WIN__) && !defined(__NETWARE__)
unknown's avatar
unknown committed
1395 1396 1397 1398 1399
  if (sig == SIGALRM)
    alarm(2);					/* reschedule alarm */
#endif
}

unknown's avatar
unknown committed
1400
#ifndef EMBEDDED_LIBRARY
1401

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
static void init_error_log_mutex()
{
  mysql_mutex_init(key_LOCK_error_log, &LOCK_error_log, MY_MUTEX_INIT_FAST);
}


static void clean_up_error_log_mutex()
{
  mysql_mutex_destroy(&LOCK_error_log);
}


unknown's avatar
unknown committed
1414 1415
/**
  cleanup all memory and end program nicely.
unknown's avatar
unknown committed
1416

1417 1418 1419
    If SIGNALS_DONT_BREAK_READ is defined, this function is called
    by the main thread. To get MySQL to shut down nicely in this case
    (Mac OS X) we have to call exit() instead if pthread_exit().
unknown's avatar
unknown committed
1420

unknown's avatar
unknown committed
1421 1422 1423
  @note
    This function never returns.
*/
1424
void unireg_end(void)
unknown's avatar
unknown committed
1425
{
unknown's avatar
unknown committed
1426
  clean_up(1);
unknown's avatar
unknown committed
1427
  my_thread_end();
1428
#if defined(SIGNALS_DONT_BREAK_READ) && !defined(__NETWARE__)
1429 1430
  exit(0);
#else
unknown's avatar
unknown committed
1431
  pthread_exit(0);				// Exit is in main thread
1432
#endif
unknown's avatar
unknown committed
1433 1434
}

1435

1436
extern "C" void unireg_abort(int exit_code)
unknown's avatar
unknown committed
1437
{
1438
  DBUG_ENTER("unireg_abort");
1439

1440 1441
  if (opt_help)
    usage();
unknown's avatar
unknown committed
1442 1443
  if (exit_code)
    sql_print_error("Aborting\n");
1444
  clean_up(!opt_help && (exit_code || !opt_bootstrap)); /* purecov: inspected */
1445
  DBUG_PRINT("quit",("done with cleanup in unireg_abort"));
1446 1447 1448 1449 1450
  mysqld_exit(exit_code);
}

static void mysqld_exit(int exit_code)
{
1451 1452 1453 1454 1455
  /*
    Important note: we wait for the signal thread to end,
    but if a kill -15 signal was sent, the signal thread did
    spawn the kill_server_thread thread, which is running concurrently.
  */
1456
  wait_for_signal_thread_to_end();
1457
  mysql_audit_finalize();
unknown's avatar
unknown committed
1458
  clean_up_mutexes();
Marc Alff's avatar
Marc Alff committed
1459
  clean_up_error_log_mutex();
unknown's avatar
unknown committed
1460
  my_end(opt_endinfo ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
unknown's avatar
unknown committed
1461 1462
  exit(exit_code); /* purecov: inspected */
}
1463

1464
#endif /* !EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
1465

1466
void clean_up(bool print_message)
unknown's avatar
unknown committed
1467 1468 1469 1470
{
  DBUG_PRINT("exit",("clean_up"));
  if (cleanup_done++)
    return; /* purecov: inspected */
unknown's avatar
unknown committed
1471

1472
  stop_handle_manager();
1473 1474
  release_ddl_log();

unknown's avatar
unknown committed
1475 1476 1477 1478 1479
  /*
    make sure that handlers finish up
    what they have that is dependent on the binlog
  */
  ha_binlog_end(current_thd);
unknown's avatar
unknown committed
1480 1481 1482

  logger.cleanup_base();

1483
  injector::free_instance();
unknown's avatar
unknown committed
1484 1485
  mysql_bin_log.cleanup();

unknown's avatar
SCRUM  
unknown committed
1486
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
1487 1488
  if (use_slave_mask)
    bitmap_free(&slave_error_mask);
1489
#endif
1490
  my_tz_free();
unknown's avatar
unknown committed
1491
  my_database_names_free();
unknown's avatar
unknown committed
1492
#ifndef NO_EMBEDDED_ACCESS_CHECKS
unknown's avatar
unknown committed
1493
  servers_free(1);
unknown's avatar
unknown committed
1494 1495
  acl_free(1);
  grant_free();
unknown's avatar
unknown committed
1496
#endif
unknown's avatar
unknown committed
1497
  query_cache_destroy();
unknown's avatar
unknown committed
1498 1499 1500
  hostname_cache_free();
  item_user_lock_free();
  lex_free();				/* Free some memory */
1501
  item_create_cleanup();
1502
  free_charsets();
unknown's avatar
unknown committed
1503
  if (!opt_noacl)
1504
  {
1505
#ifdef HAVE_DLOPEN
unknown's avatar
unknown committed
1506
    udf_free();
1507
#endif
1508
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
1509
  table_def_start_shutdown();
1510
  plugin_shutdown();
1511
  ha_end();
unknown's avatar
Merge  
unknown committed
1512 1513
  if (tc_log)
    tc_log->close();
He Zhenxing's avatar
He Zhenxing committed
1514
  delegates_destroy();
1515
  xid_cache_free();
Konstantin Osipov's avatar
Konstantin Osipov committed
1516 1517
  table_def_free();
  mdl_destroy();
1518
  key_caches.delete_elements((void (*)(const char*, uchar*)) free_key_cache);
1519
  multi_keycache_free();
1520
  free_status_vars();
1521
  end_thr_alarm(1);			/* Free allocated memory */
1522
  my_free_open_file_info();
unknown's avatar
unknown committed
1523 1524
  if (defaults_argv)
    free_defaults(defaults_argv);
unknown's avatar
unknown committed
1525
  free_tmpdir(&mysql_tmpdir_list);
1526
  x_free(opt_bin_logname);
unknown's avatar
unknown committed
1527
  bitmap_free(&temp_pool);
unknown's avatar
unknown committed
1528
  free_max_user_conn();
unknown's avatar
SCRUM  
unknown committed
1529
#ifdef HAVE_REPLICATION
1530
  end_slave_list();
1531
#endif
unknown's avatar
unknown committed
1532 1533
  delete binlog_filter;
  delete rpl_filter;
1534
  end_ssl();
1535
  vio_end();
unknown's avatar
unknown committed
1536
#ifdef USE_REGEX
unknown's avatar
unknown committed
1537
  my_regex_end();
unknown's avatar
unknown committed
1538
#endif
1539 1540 1541 1542
#if defined(ENABLED_DEBUG_SYNC)
  /* End the debug sync facility. See debug_sync.cc. */
  debug_sync_end();
#endif /* defined(ENABLED_DEBUG_SYNC) */
unknown's avatar
unknown committed
1543

1544
#if !defined(EMBEDDED_LIBRARY)
1545
  if (!opt_bootstrap)
Marc Alff's avatar
Marc Alff committed
1546
    mysql_file_delete(key_file_pid, pidfile_name, MYF(0)); // This may not always exist
unknown's avatar
unknown committed
1547
#endif
1548
  if (print_message && my_default_lc_messages && server_start_time)
1549 1550
    sql_print_information(ER_DEFAULT(ER_SHUTDOWN_COMPLETE),my_progname);
  cleanup_errmsgs();
unknown's avatar
unknown committed
1551
  thread_scheduler.end();
unknown's avatar
Merge  
unknown committed
1552
  finish_client_errs();
1553
  DBUG_PRINT("quit", ("Error messages freed"));
unknown's avatar
unknown committed
1554
  /* Tell main we are ready */
unknown's avatar
unknown committed
1555
  logger.cleanup_end();
1556
  my_atomic_rwlock_destroy(&global_query_id_lock);
1557
  my_atomic_rwlock_destroy(&thread_running_lock);
Marc Alff's avatar
Marc Alff committed
1558
  mysql_mutex_lock(&LOCK_thread_count);
1559
  DBUG_PRINT("quit", ("got thread count lock"));
unknown's avatar
unknown committed
1560
  ready_to_exit=1;
unknown's avatar
unknown committed
1561
  /* do the broadcast inside the lock to ensure that my_end() is not called */
Marc Alff's avatar
Marc Alff committed
1562 1563
  mysql_cond_broadcast(&COND_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);
1564
  sys_var_end();
unknown's avatar
unknown committed
1565

unknown's avatar
unknown committed
1566 1567 1568 1569
  /*
    The following lines may never be executed as the main thread may have
    killed us
  */
1570
  DBUG_PRINT("quit", ("done with cleanup"));
unknown's avatar
unknown committed
1571 1572 1573
} /* clean_up */


1574 1575
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
1576
/**
1577
  This is mainly needed when running with purify, but it's still nice to
unknown's avatar
unknown committed
1578
  know that all child threads have died when mysqld exits.
1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
*/
static void wait_for_signal_thread_to_end()
{
#ifndef __NETWARE__
  uint i;
  /*
    Wait up to 10 seconds for signal thread to die. We use this mainly to
    avoid getting warnings that my_thread_end has not been called
  */
  for (i= 0 ; i < 100 && signal_thread_in_use; i++)
  {
1590
    if (pthread_kill(signal_thread, MYSQL_KILL_SIGNAL) != ESRCH)
1591 1592 1593 1594 1595 1596 1597
      break;
    my_sleep(100);				// Give it time to die
  }
#endif
}


unknown's avatar
unknown committed
1598 1599
static void clean_up_mutexes()
{
Marc Alff's avatar
Marc Alff committed
1600 1601
  mysql_mutex_destroy(&LOCK_mysql_create_db);
  mysql_mutex_destroy(&LOCK_lock_db);
Marc Alff's avatar
Marc Alff committed
1602
  mysql_rwlock_destroy(&LOCK_grant);
Marc Alff's avatar
Marc Alff committed
1603
  mysql_mutex_destroy(&LOCK_open);
Marc Alff's avatar
Marc Alff committed
1604
  mysql_mutex_destroy(&LOCK_thread_count);
Marc Alff's avatar
Marc Alff committed
1605
  mysql_mutex_destroy(&LOCK_mapped_file);
Marc Alff's avatar
Marc Alff committed
1606 1607 1608 1609
  mysql_mutex_destroy(&LOCK_status);
  mysql_mutex_destroy(&LOCK_delayed_insert);
  mysql_mutex_destroy(&LOCK_delayed_status);
  mysql_mutex_destroy(&LOCK_delayed_create);
Marc Alff's avatar
Marc Alff committed
1610 1611 1612 1613
  mysql_mutex_destroy(&LOCK_manager);
  mysql_mutex_destroy(&LOCK_crypt);
  mysql_mutex_destroy(&LOCK_user_conn);
  mysql_mutex_destroy(&LOCK_connection_count);
1614
  Events::destroy_mutexes();
1615
#ifdef HAVE_OPENSSL
Marc Alff's avatar
Marc Alff committed
1616
  mysql_mutex_destroy(&LOCK_des_key_file);
unknown's avatar
unknown committed
1617
#ifndef HAVE_YASSL
1618
  for (int i= 0; i < CRYPTO_num_locks(); ++i)
1619
    mysql_rwlock_destroy(&openssl_stdlocks[i].lock);
1620
  OPENSSL_free(openssl_stdlocks);
1621 1622
#endif
#endif
1623
#ifdef HAVE_REPLICATION
Marc Alff's avatar
Marc Alff committed
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
  mysql_mutex_destroy(&LOCK_rpl_status);
  mysql_cond_destroy(&COND_rpl_status);
#endif
  mysql_mutex_destroy(&LOCK_active_mi);
  mysql_rwlock_destroy(&LOCK_sys_init_connect);
  mysql_rwlock_destroy(&LOCK_sys_init_slave);
  mysql_mutex_destroy(&LOCK_global_system_variables);
  mysql_rwlock_destroy(&LOCK_system_variables_hash);
  mysql_mutex_destroy(&LOCK_global_read_lock);
  mysql_mutex_destroy(&LOCK_uuid_generator);
  mysql_mutex_destroy(&LOCK_prepared_stmt_count);
  mysql_mutex_destroy(&LOCK_error_messages);
Marc Alff's avatar
Marc Alff committed
1636
  mysql_cond_destroy(&COND_thread_count);
Marc Alff's avatar
Marc Alff committed
1637
  mysql_cond_destroy(&COND_refresh);
Marc Alff's avatar
Marc Alff committed
1638
  mysql_cond_destroy(&COND_global_read_lock);
Marc Alff's avatar
Marc Alff committed
1639 1640
  mysql_cond_destroy(&COND_thread_cache);
  mysql_cond_destroy(&COND_flush_thread_cache);
Marc Alff's avatar
Marc Alff committed
1641
  mysql_cond_destroy(&COND_manager);
unknown's avatar
unknown committed
1642
}
1643 1644 1645
#endif /*EMBEDDED_LIBRARY*/


unknown's avatar
unknown committed
1646 1647 1648 1649
/****************************************************************************
** Init IP and UNIX socket
****************************************************************************/

unknown's avatar
unknown committed
1650
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
1651 1652 1653
static void set_ports()
{
  char	*env;
1654
  if (!mysqld_port && !opt_disable_networking)
unknown's avatar
unknown committed
1655
  {					// Get port if not from commandline
1656
    mysqld_port= MYSQL_PORT;
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668

    /*
      if builder specifically requested a default port, use that
      (even if it coincides with our factory default).
      only if they didn't do we check /etc/services (and, failing
      on that, fall back to the factory default of 3306).
      either default can be overridden by the environment variable
      MYSQL_TCP_PORT, which in turn can be overridden with command
      line options.
    */

#if MYSQL_PORT_DEFAULT == 0
unknown's avatar
unknown committed
1669
    struct  servent *serv_ptr;
1670 1671
    if ((serv_ptr= getservbyname("mysql", "tcp")))
      mysqld_port= ntohs((u_short) serv_ptr->s_port); /* purecov: inspected */
1672
#endif
unknown's avatar
unknown committed
1673
    if ((env = getenv("MYSQL_TCP_PORT")))
1674
      mysqld_port= (uint) atoi(env);		/* purecov: inspected */
unknown's avatar
unknown committed
1675
  }
1676
  if (!mysqld_unix_port)
unknown's avatar
unknown committed
1677 1678
  {
#ifdef __WIN__
1679
    mysqld_unix_port= (char*) MYSQL_NAMEDPIPE;
unknown's avatar
unknown committed
1680
#else
1681
    mysqld_unix_port= (char*) MYSQL_UNIX_ADDR;
unknown's avatar
unknown committed
1682 1683
#endif
    if ((env = getenv("MYSQL_UNIX_PORT")))
1684
      mysqld_unix_port= env;			/* purecov: inspected */
unknown's avatar
unknown committed
1685 1686 1687 1688 1689
  }
}

/* Change to run as another user if started with --user */

1690
static struct passwd *check_user(const char *user)
unknown's avatar
unknown committed
1691
{
1692
#if !defined(__WIN__) && !defined(__NETWARE__)
1693
  struct passwd *tmp_user_info;
1694
  uid_t user_id= geteuid();
unknown's avatar
unknown committed
1695

1696
  // Don't bother if we aren't superuser
1697
  if (user_id)
unknown's avatar
unknown committed
1698 1699
  {
    if (user)
1700
    {
1701 1702 1703 1704
      /* Don't give a warning, if real user is same as given with --user */
      /* purecov: begin tested */
      tmp_user_info= getpwnam(user);
      if ((!tmp_user_info || user_id != tmp_user_info->pw_uid) &&
1705
	  global_system_variables.log_warnings)
1706 1707
        sql_print_warning(
                    "One can only use the --user switch if running as root\n");
unknown's avatar
unknown committed
1708
      /* purecov: end */
1709
    }
1710
    return NULL;
unknown's avatar
unknown committed
1711
  }
1712
  if (!user)
unknown's avatar
unknown committed
1713 1714 1715
  {
    if (!opt_bootstrap)
    {
unknown's avatar
unknown committed
1716
      sql_print_error("Fatal error: Please read \"Security\" section of the manual to find out how to run mysqld as root!\n");
unknown's avatar
unknown committed
1717 1718
      unireg_abort(1);
    }
1719
    return NULL;
unknown's avatar
unknown committed
1720
  }
1721
  /* purecov: begin tested */
unknown's avatar
unknown committed
1722
  if (!strcmp(user,"root"))
unknown's avatar
unknown committed
1723
    return NULL;                        // Avoid problem with dynamic libraries
unknown's avatar
unknown committed
1724

1725
  if (!(tmp_user_info= getpwnam(user)))
unknown's avatar
unknown committed
1726
  {
1727
    // Allow a numeric uid to be used
unknown's avatar
unknown committed
1728
    const char *pos;
unknown's avatar
unknown committed
1729 1730
    for (pos= user; my_isdigit(mysqld_charset,*pos); pos++) ;
    if (*pos)                                   // Not numeric id
1731
      goto err;
1732
    if (!(tmp_user_info= getpwuid(atoi(user))))
1733
      goto err;
unknown's avatar
unknown committed
1734
  }
unknown's avatar
unknown committed
1735 1736
  return tmp_user_info;
  /* purecov: end */
1737 1738

err:
unknown's avatar
unknown committed
1739
  sql_print_error("Fatal error: Can't change to run as user '%s' ;  Please check that the user exists!\n",user);
1740
  unireg_abort(1);
1741 1742 1743 1744 1745 1746 1747 1748 1749

#ifdef PR_SET_DUMPABLE
  if (test_flags & TEST_CORE_ON_SIGNAL)
  {
    /* inform kernel that process is dumpable */
    (void) prctl(PR_SET_DUMPABLE, 1);
  }
#endif

unknown's avatar
unknown committed
1750 1751
#endif
  return NULL;
1752 1753
}

1754
static void set_user(const char *user, struct passwd *user_info_arg)
1755
{
1756
  /* purecov: begin tested */
1757
#if !defined(__WIN__) && !defined(__NETWARE__)
1758
  DBUG_ASSERT(user_info_arg != 0);
unknown's avatar
unknown committed
1759
#ifdef HAVE_INITGROUPS
1760 1761 1762 1763 1764 1765 1766
  /*
    We can get a SIGSEGV when calling initgroups() on some systems when NSS
    is configured to use LDAP and the server is statically linked.  We set
    calling_initgroups as a flag to the SIGSEGV handler that is then used to
    output a specific message to help the user resolve this problem.
  */
  calling_initgroups= TRUE;
1767
  initgroups((char*) user, user_info_arg->pw_gid);
1768
  calling_initgroups= FALSE;
unknown's avatar
unknown committed
1769
#endif
1770
  if (setgid(user_info_arg->pw_gid) == -1)
1771 1772 1773
  {
    sql_perror("setgid");
    unireg_abort(1);
unknown's avatar
unknown committed
1774
  }
1775
  if (setuid(user_info_arg->pw_uid) == -1)
unknown's avatar
unknown committed
1776 1777 1778 1779 1780
  {
    sql_perror("setuid");
    unireg_abort(1);
  }
#endif
unknown's avatar
unknown committed
1781
  /* purecov: end */
unknown's avatar
unknown committed
1782 1783
}

unknown's avatar
unknown committed
1784

1785
static void set_effective_user(struct passwd *user_info_arg)
1786
{
1787
#if !defined(__WIN__) && !defined(__NETWARE__)
1788 1789
  DBUG_ASSERT(user_info_arg != 0);
  if (setregid((gid_t)-1, user_info_arg->pw_gid) == -1)
1790
  {
1791
    sql_perror("setregid");
1792
    unireg_abort(1);
unknown's avatar
unknown committed
1793
  }
1794
  if (setreuid((uid_t)-1, user_info_arg->pw_uid) == -1)
1795
  {
1796
    sql_perror("setreuid");
1797 1798 1799 1800 1801 1802
    unireg_abort(1);
  }
#endif
}


unknown's avatar
unknown committed
1803
/** Change root user if started with @c --chroot . */
unknown's avatar
unknown committed
1804 1805
static void set_root(const char *path)
{
1806
#if !defined(__WIN__) && !defined(__NETWARE__)
unknown's avatar
unknown committed
1807 1808 1809 1810 1811
  if (chroot(path) == -1)
  {
    sql_perror("chroot");
    unireg_abort(1);
  }
1812
  my_setwd("/", MYF(0));
unknown's avatar
unknown committed
1813 1814 1815
#endif
}

1816

unknown's avatar
unknown committed
1817
static void network_init(void)
unknown's avatar
unknown committed
1818 1819 1820 1821
{
#ifdef HAVE_SYS_UN_H
  struct sockaddr_un	UNIXaddr;
#endif
1822
  int	arg;
1823 1824 1825 1826
  int   ret;
  uint  waited;
  uint  this_wait;
  uint  retry;
1827
  char port_buf[NI_MAXSERV];
unknown's avatar
unknown committed
1828
  DBUG_ENTER("network_init");
1829
  LINT_INIT(ret);
unknown's avatar
unknown committed
1830

unknown's avatar
unknown committed
1831 1832 1833
  if (thread_scheduler.init())
    unireg_abort(1);			/* purecov: inspected */

unknown's avatar
unknown committed
1834 1835
  set_ports();

1836
  if (mysqld_port != 0 && !opt_disable_networking && !opt_bootstrap)
unknown's avatar
unknown committed
1837
  {
1838 1839 1840
    struct addrinfo *ai, *a;
    struct addrinfo hints;
    int error;
1841
    DBUG_PRINT("general",("IP Socket is %d",mysqld_port));
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852

    bzero(&hints, sizeof (hints));
    hints.ai_flags= AI_PASSIVE;
    hints.ai_socktype= SOCK_STREAM;
    hints.ai_family= AF_UNSPEC;

    my_snprintf(port_buf, NI_MAXSERV, "%d", mysqld_port);
    error= getaddrinfo(my_bind_addr_str, port_buf, &hints, &ai);
    if (error != 0)
    {
      DBUG_PRINT("error",("Got error: %d from getaddrinfo()", error));
1853
      sql_perror(ER_DEFAULT(ER_IPSOCK_ERROR));  /* purecov: tested */
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
      unireg_abort(1);				/* purecov: tested */
    }

    for (a= ai; a != NULL; a= a->ai_next)
    {
      ip_sock= socket(a->ai_family, a->ai_socktype, a->ai_protocol);
      if (ip_sock != INVALID_SOCKET)
        break;
    }

unknown's avatar
unknown committed
1864 1865 1866
    if (ip_sock == INVALID_SOCKET)
    {
      DBUG_PRINT("error",("Got error: %d from socket()",socket_errno));
1867
      sql_perror(ER_DEFAULT(ER_IPSOCK_ERROR));  /* purecov: tested */
unknown's avatar
unknown committed
1868 1869
      unireg_abort(1);				/* purecov: tested */
    }
1870 1871 1872 1873 1874 1875

#ifndef __WIN__
    /*
      We should not use SO_REUSEADDR on windows as this would enable a
      user to open two mysqld servers with the same TCP/IP port.
    */
1876
    arg= 1;
unknown's avatar
unknown committed
1877
    (void) setsockopt(ip_sock,SOL_SOCKET,SO_REUSEADDR,(char*)&arg,sizeof(arg));
unknown's avatar
unknown committed
1878
#endif /* __WIN__ */
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896

#ifdef IPV6_V6ONLY
     /*
       For interoperability with older clients, IPv6 socket should
       listen on both IPv6 and IPv4 wildcard addresses.
       Turn off IPV6_V6ONLY option.

       NOTE: this will work starting from Windows Vista only.
       On Windows XP dual stack is not available, so it will not
       listen on the corresponding IPv4-address.
     */
    if (a->ai_family == AF_INET6)
    {
      arg= 0;
      (void) setsockopt(ip_sock, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&arg,
                sizeof(arg));
    }
#endif
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    /*
      Sometimes the port is not released fast enough when stopping and
      restarting the server. This happens quite often with the test suite
      on busy Linux systems. Retry to bind the address at these intervals:
      Sleep intervals: 1, 2, 4,  6,  9, 13, 17, 22, ...
      Retry at second: 1, 3, 7, 13, 22, 35, 52, 74, ...
      Limit the sequence by mysqld_port_timeout (set --port-open-timeout=#).
    */
    for (waited= 0, retry= 1; ; retry++, waited+= this_wait)
    {
1907
      if (((ret= bind(ip_sock, a->ai_addr, a->ai_addrlen)) >= 0 ) ||
1908
          (socket_errno != SOCKET_EADDRINUSE) ||
1909 1910 1911 1912 1913 1914
          (waited >= mysqld_port_timeout))
        break;
      sql_print_information("Retrying bind on TCP/IP port %u", mysqld_port);
      this_wait= retry * retry / 3 + 1;
      sleep(this_wait);
    }
1915
    freeaddrinfo(ai);
1916
    if (ret < 0)
unknown's avatar
unknown committed
1917 1918
    {
      DBUG_PRINT("error",("Got error: %d from bind",socket_errno));
1919
      sql_perror("Can't start server: Bind on TCP/IP port");
1920
      sql_print_error("Do you already have another mysqld server running on port: %d ?",mysqld_port);
unknown's avatar
unknown committed
1921 1922
      unireg_abort(1);
    }
1923
    if (listen(ip_sock,(int) back_log) < 0)
unknown's avatar
unknown committed
1924
    {
1925
      sql_perror("Can't start server: listen() on TCP/IP port");
1926
      sql_print_error("listen() on TCP/IP failed with error %d",
unknown's avatar
unknown committed
1927
		      socket_errno);
unknown's avatar
unknown committed
1928 1929
      unireg_abort(1);
    }
unknown's avatar
unknown committed
1930
  }
1931

Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
1932
#ifdef _WIN32
unknown's avatar
unknown committed
1933
  /* create named pipe */
1934
  if (Service.IsNT() && mysqld_unix_port[0] && !opt_bootstrap &&
unknown's avatar
unknown committed
1935
      opt_enable_named_pipe)
unknown's avatar
unknown committed
1936
  {
1937
    strxnmov(pipe_name, sizeof(pipe_name)-1, "\\\\.\\pipe\\",
1938
	     mysqld_unix_port, NullS);
1939 1940
    bzero((char*) &saPipeSecurity, sizeof(saPipeSecurity));
    bzero((char*) &sdPipeDescriptor, sizeof(sdPipeDescriptor));
1941
    if (!InitializeSecurityDescriptor(&sdPipeDescriptor,
1942
				      SECURITY_DESCRIPTOR_REVISION))
unknown's avatar
unknown committed
1943 1944 1945 1946 1947 1948 1949 1950 1951
    {
      sql_perror("Can't start server : Initialize security descriptor");
      unireg_abort(1);
    }
    if (!SetSecurityDescriptorDacl(&sdPipeDescriptor, TRUE, NULL, FALSE))
    {
      sql_perror("Can't start server : Set security descriptor");
      unireg_abort(1);
    }
unknown's avatar
Merge  
unknown committed
1952
    saPipeSecurity.nLength = sizeof(SECURITY_ATTRIBUTES);
unknown's avatar
unknown committed
1953 1954
    saPipeSecurity.lpSecurityDescriptor = &sdPipeDescriptor;
    saPipeSecurity.bInheritHandle = FALSE;
1955
    if ((hPipe= CreateNamedPipe(pipe_name,
1956
				PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
1957 1958 1959 1960 1961 1962 1963 1964
				PIPE_TYPE_BYTE |
				PIPE_READMODE_BYTE |
				PIPE_WAIT,
				PIPE_UNLIMITED_INSTANCES,
				(int) global_system_variables.net_buffer_length,
				(int) global_system_variables.net_buffer_length,
				NMPWAIT_USE_DEFAULT_WAIT,
				&saPipeSecurity)) == INVALID_HANDLE_VALUE)
unknown's avatar
unknown committed
1965 1966 1967 1968 1969 1970 1971
      {
	LPVOID lpMsgBuf;
	int error=GetLastError();
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
		      FORMAT_MESSAGE_FROM_SYSTEM,
		      NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		      (LPTSTR) &lpMsgBuf, 0, NULL );
1972
	sql_perror((char *)lpMsgBuf);
unknown's avatar
Merge  
unknown committed
1973
	LocalFree(lpMsgBuf);
unknown's avatar
unknown committed
1974 1975 1976 1977 1978
	unireg_abort(1);
      }
  }
#endif

1979
#if defined(HAVE_SYS_UN_H)
unknown's avatar
unknown committed
1980 1981 1982
  /*
  ** Create the UNIX socket
  */
1983
  if (mysqld_unix_port[0] && !opt_bootstrap)
unknown's avatar
unknown committed
1984
  {
1985
    DBUG_PRINT("general",("UNIX Socket is %s",mysqld_unix_port));
unknown's avatar
unknown committed
1986

unknown's avatar
unknown committed
1987 1988
    if (strlen(mysqld_unix_port) > (sizeof(UNIXaddr.sun_path) - 1))
    {
1989
      sql_print_error("The socket file path is too long (> %u): %s",
unknown's avatar
unknown committed
1990
                      (uint) sizeof(UNIXaddr.sun_path) - 1, mysqld_unix_port);
unknown's avatar
unknown committed
1991 1992
      unireg_abort(1);
    }
1993
    if ((unix_sock= socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
unknown's avatar
unknown committed
1994 1995 1996 1997 1998 1999
    {
      sql_perror("Can't start server : UNIX Socket "); /* purecov: inspected */
      unireg_abort(1);				/* purecov: inspected */
    }
    bzero((char*) &UNIXaddr, sizeof(UNIXaddr));
    UNIXaddr.sun_family = AF_UNIX;
2000 2001
    strmov(UNIXaddr.sun_path, mysqld_unix_port);
    (void) unlink(mysqld_unix_port);
2002
    arg= 1;
unknown's avatar
unknown committed
2003 2004 2005 2006 2007 2008 2009
    (void) setsockopt(unix_sock,SOL_SOCKET,SO_REUSEADDR,(char*)&arg,
		      sizeof(arg));
    umask(0);
    if (bind(unix_sock, my_reinterpret_cast(struct sockaddr *) (&UNIXaddr),
	     sizeof(UNIXaddr)) < 0)
    {
      sql_perror("Can't start server : Bind on unix socket"); /* purecov: tested */
2010
      sql_print_error("Do you already have another mysqld server running on socket: %s ?",mysqld_unix_port);
unknown's avatar
unknown committed
2011 2012 2013 2014
      unireg_abort(1);					/* purecov: tested */
    }
    umask(((~my_umask) & 0666));
#if defined(S_IFSOCK) && defined(SECURE_SOCKETS)
2015
    (void) chmod(mysqld_unix_port,S_IFSOCK);	/* Fix solaris 2.6 bug */
unknown's avatar
unknown committed
2016
#endif
2017
    if (listen(unix_sock,(int) back_log) < 0)
2018
      sql_print_warning("listen() on Unix socket failed with error %d",
unknown's avatar
unknown committed
2019
		      socket_errno);
unknown's avatar
unknown committed
2020 2021 2022 2023 2024 2025
  }
#endif
  DBUG_PRINT("info",("server started"));
  DBUG_VOID_RETURN;
}

2026
#endif /*!EMBEDDED_LIBRARY*/
unknown's avatar
unknown committed
2027

2028

2029
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2030 2031
/**
  Close a connection.
2032

unknown's avatar
unknown committed
2033 2034 2035
  @param thd		Thread handle
  @param errcode	Error code to print to console
  @param lock	        1 if we have have to lock LOCK_thread_count
2036

unknown's avatar
unknown committed
2037
  @note
2038 2039
    For the connection that is doing shutdown, this is called twice
*/
2040
void close_connection(THD *thd, uint errcode, bool lock)
unknown's avatar
unknown committed
2041
{
2042
  st_vio *vio;
unknown's avatar
unknown committed
2043 2044
  DBUG_ENTER("close_connection");
  DBUG_PRINT("enter",("fd: %s  error: '%s'",
2045 2046
		      thd->net.vio ? vio_description(thd->net.vio) :
		      "(not connected)",
2047
		      errcode ? ER_DEFAULT(errcode) : ""));
unknown's avatar
unknown committed
2048
  if (lock)
Marc Alff's avatar
Marc Alff committed
2049
    mysql_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
2050 2051
  thd->killed= THD::KILL_CONNECTION;
  if ((vio= thd->net.vio) != 0)
unknown's avatar
unknown committed
2052 2053
  {
    if (errcode)
Marc Alff's avatar
Marc Alff committed
2054
      net_send_error(thd, errcode,
2055
                     ER_DEFAULT(errcode), NULL); /* purecov: inspected */
unknown's avatar
unknown committed
2056 2057 2058
    vio_close(vio);			/* vio is freed in delete thd */
  }
  if (lock)
Marc Alff's avatar
Marc Alff committed
2059
    mysql_mutex_unlock(&LOCK_thread_count);
2060 2061 2062 2063 2064
  MYSQL_CONNECTION_DONE((int) errcode, thd->thread_id);
  if (MYSQL_CONNECTION_DONE_ENABLED())
  {
    sleep(0); /* Workaround to avoid tailcall optimisation */
  }
unknown's avatar
unknown committed
2065 2066
  DBUG_VOID_RETURN;
}
2067 2068
#endif /* EMBEDDED_LIBRARY */

unknown's avatar
unknown committed
2069

unknown's avatar
unknown committed
2070 2071
/** Called when a thread is aborted. */
/* ARGSUSED */
2072
extern "C" sig_handler end_thread_signal(int sig __attribute__((unused)))
unknown's avatar
unknown committed
2073 2074 2075
{
  THD *thd=current_thd;
  DBUG_ENTER("end_thread_signal");
2076
  if (thd && ! thd->bootstrap)
2077 2078
  {
    statistic_increment(killed_threads, &LOCK_status);
unknown's avatar
unknown committed
2079
    thread_scheduler.end_thread(thd,0);		/* purecov: inspected */
2080
  }
unknown's avatar
unknown committed
2081 2082 2083 2084
  DBUG_VOID_RETURN;				/* purecov: deadcode */
}


unknown's avatar
unknown committed
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096
/*
  Unlink thd from global list of available connections and free thd

  SYNOPSIS
    unlink_thd()
    thd		 Thread handler

  NOTES
    LOCK_thread_count is locked and left locked
*/

void unlink_thd(THD *thd)
unknown's avatar
unknown committed
2097
{
unknown's avatar
unknown committed
2098 2099
  DBUG_ENTER("unlink_thd");
  DBUG_PRINT("enter", ("thd: 0x%lx", (long) thd));
unknown's avatar
unknown committed
2100
  thd->cleanup();
2101

Marc Alff's avatar
Marc Alff committed
2102
  mysql_mutex_lock(&LOCK_connection_count);
2103
  --connection_count;
Marc Alff's avatar
Marc Alff committed
2104
  mysql_mutex_unlock(&LOCK_connection_count);
2105

Marc Alff's avatar
Marc Alff committed
2106
  mysql_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
2107 2108
  thread_count--;
  delete thd;
unknown's avatar
unknown committed
2109 2110 2111
  DBUG_VOID_RETURN;
}

2112

unknown's avatar
unknown committed
2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
/*
  Store thread in cache for reuse by new connections

  SYNOPSIS
    cache_thread()

  NOTES
    LOCK_thread_count has to be locked

  RETURN
    0  Thread was not put in cache
    1  Thread is to be reused by new connection.
       (ie, caller should return, not abort with pthread_exit())
*/


static bool cache_thread()
{
Marc Alff's avatar
Marc Alff committed
2131
  mysql_mutex_assert_owner(&LOCK_thread_count);
unknown's avatar
unknown committed
2132
  if (cached_thread_count < thread_cache_size &&
2133
      ! abort_loop && !kill_cached_threads)
unknown's avatar
unknown committed
2134 2135
  {
    /* Don't kill the thread, just put it in cache for reuse */
unknown's avatar
unknown committed
2136
    DBUG_PRINT("info", ("Adding thread to cache"));
unknown's avatar
unknown committed
2137 2138
    cached_thread_count++;
    while (!abort_loop && ! wake_thread && ! kill_cached_threads)
Marc Alff's avatar
Marc Alff committed
2139
      mysql_cond_wait(&COND_thread_cache, &LOCK_thread_count);
unknown's avatar
unknown committed
2140 2141
    cached_thread_count--;
    if (kill_cached_threads)
Marc Alff's avatar
Marc Alff committed
2142
      mysql_cond_signal(&COND_flush_thread_cache);
unknown's avatar
unknown committed
2143 2144
    if (wake_thread)
    {
unknown's avatar
unknown committed
2145
      THD *thd;
unknown's avatar
unknown committed
2146
      wake_thread--;
unknown's avatar
unknown committed
2147
      thd= thread_cache.get();
2148
      thd->thread_stack= (char*) &thd;          // For store_globals
unknown's avatar
unknown committed
2149
      (void) thd->store_globals();
2150 2151 2152 2153 2154 2155
      /*
        THD::mysys_var::abort is associated with physical thread rather
        than with THD object. So we need to reset this flag before using
        this thread for handling of new THD object/connection.
      */
      thd->mysys_var->abort= 0;
2156
      thd->thr_create_utime= my_micro_time();
2157
      threads.append(thd);
unknown's avatar
unknown committed
2158
      return(1);
unknown's avatar
unknown committed
2159 2160
    }
  }
unknown's avatar
unknown committed
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
  return(0);
}


/*
  End thread for the current connection

  SYNOPSIS
    one_thread_per_connection_end()
    thd		  Thread handler
    put_in_cache  Store thread in cache, if there is room in it
                  Normally this is true in all cases except when we got
                  out of resources initializing the current thread

  NOTES
    If thread is cached, we will wait until thread is scheduled to be
    reused and then we will return.
    If thread is not cached, we end the thread.

  RETURN
    0    Signal to handle_one_connection to reuse connection
*/

bool one_thread_per_connection_end(THD *thd, bool put_in_cache)
{
  DBUG_ENTER("one_thread_per_connection_end");
  unlink_thd(thd);
  if (put_in_cache)
    put_in_cache= cache_thread();
Marc Alff's avatar
Marc Alff committed
2190
  mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
2191 2192
  if (put_in_cache)
    DBUG_RETURN(0);                             // Thread is reused
unknown's avatar
unknown committed
2193

2194
  /* It's safe to broadcast outside a lock (COND... is not deleted here) */
unknown's avatar
unknown committed
2195
  DBUG_PRINT("signal", ("Broadcasting COND_thread_count"));
2196
  DBUG_LEAVE;                                   // Must match DBUG_ENTER()
2197
  my_thread_end();
Marc Alff's avatar
Marc Alff committed
2198
  mysql_cond_broadcast(&COND_thread_count);
unknown's avatar
unknown committed
2199 2200

  pthread_exit(0);
2201
  return 0;                                     // Avoid compiler warnings
unknown's avatar
unknown committed
2202 2203 2204 2205 2206
}


void flush_thread_cache()
{
Marc Alff's avatar
Marc Alff committed
2207
  mysql_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
2208 2209 2210
  kill_cached_threads++;
  while (cached_thread_count)
  {
Marc Alff's avatar
Marc Alff committed
2211 2212
    mysql_cond_broadcast(&COND_thread_cache);
    mysql_cond_wait(&COND_flush_thread_cache, &LOCK_thread_count);
unknown's avatar
unknown committed
2213 2214
  }
  kill_cached_threads--;
Marc Alff's avatar
Marc Alff committed
2215
  mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
2216 2217 2218 2219
}


#ifdef THREAD_SPECIFIC_SIGPIPE
unknown's avatar
unknown committed
2220 2221 2222 2223 2224 2225
/**
  Aborts a thread nicely. Comes here on SIGPIPE.

  @todo
    One should have to fix that thr_alarm know about this thread too.
*/
2226
extern "C" sig_handler abort_thread(int sig __attribute__((unused)))
unknown's avatar
unknown committed
2227 2228 2229 2230
{
  THD *thd=current_thd;
  DBUG_ENTER("abort_thread");
  if (thd)
unknown's avatar
Merge  
unknown committed
2231
    thd->killed= THD::KILL_CONNECTION;
unknown's avatar
unknown committed
2232 2233 2234 2235
  DBUG_VOID_RETURN;
}
#endif

unknown's avatar
unknown committed
2236

unknown's avatar
unknown committed
2237
/******************************************************************************
2238 2239 2240
  Setup a signal thread with handles all signals.
  Because Linux doesn't support schemas use a mutex to check that
  the signal thread is ready before continuing
unknown's avatar
unknown committed
2241 2242
******************************************************************************/

2243
#if defined(__WIN__)
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257


/*
  On Windows, we use native SetConsoleCtrlHandler for handle events like Ctrl-C
  with graceful shutdown.
  Also, we do not use signal(), but SetUnhandledExceptionFilter instead - as it
  provides possibility to pass the exception to just-in-time debugger, collect
  dumps and potentially also the exception and thread context used to output
  callstack.
*/

static BOOL WINAPI console_event_handler( DWORD type ) 
{
  DBUG_ENTER("console_event_handler");
unknown's avatar
unknown committed
2258
#ifndef EMBEDDED_LIBRARY
2259 2260 2261 2262 2263 2264 2265 2266
  if(type == CTRL_C_EVENT)
  {
     /*
       Do not shutdown before startup is finished and shutdown
       thread is initialized. Otherwise there is a race condition 
       between main thread doing initialization and CTRL-C thread doing
       cleanup, which can result into crash.
     */
2267
#ifndef EMBEDDED_LIBRARY
2268 2269 2270
     if(hEventShutdown)
       kill_mysql();
     else
2271
#endif
2272 2273 2274
       sql_print_warning("CTRL-C ignored during startup");
     DBUG_RETURN(TRUE);
  }
unknown's avatar
unknown committed
2275
#endif
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
  DBUG_RETURN(FALSE);
}




#ifdef DEBUG_UNHANDLED_EXCEPTION_FILTER
#define DEBUGGER_ATTACH_TIMEOUT 120
/*
  Wait for debugger to attach and break into debugger. If debugger is not attached,
  resume after timeout.
*/
static void wait_for_debugger(int timeout_sec)
{
   if(!IsDebuggerPresent())
   {
     int i;
     printf("Waiting for debugger to attach, pid=%u\n",GetCurrentProcessId());
     fflush(stdout);
     for(i= 0; i < timeout_sec; i++)
     {
       Sleep(1000);
       if(IsDebuggerPresent())
       {
         /* Break into debugger */
         __debugbreak();
         return;
       }
     }
     printf("pid=%u, debugger not attached after %d seconds, resuming\n",GetCurrentProcessId(),
       timeout_sec);
     fflush(stdout);
   }
}
#endif /* DEBUG_UNHANDLED_EXCEPTION_FILTER */

LONG WINAPI my_unhandler_exception_filter(EXCEPTION_POINTERS *ex_pointers)
{
   static BOOL first_time= TRUE;
   if(!first_time)
   {
     /*
       This routine can be called twice, typically
       when detaching in JIT debugger.
       Return EXCEPTION_EXECUTE_HANDLER to terminate process.
     */
     return EXCEPTION_EXECUTE_HANDLER;
   }
   first_time= FALSE;
#ifdef DEBUG_UNHANDLED_EXCEPTION_FILTER
   /*
    Unfortunately there is no clean way to debug unhandled exception filters,
    as debugger does not stop there(also documented in MSDN) 
    To overcome, one could put a MessageBox, but this will not work in service.
    Better solution is to print error message and sleep some minutes 
    until debugger is attached
  */
  wait_for_debugger(DEBUGGER_ATTACH_TIMEOUT);
#endif /* DEBUG_UNHANDLED_EXCEPTION_FILTER */
  __try
  {
2337
    my_set_exception_pointers(ex_pointers);
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
    handle_segfault(ex_pointers->ExceptionRecord->ExceptionCode);
  }
  __except(EXCEPTION_EXECUTE_HANDLER)
  {
    DWORD written;
    const char msg[] = "Got exception in exception handler!\n";
    WriteFile(GetStdHandle(STD_OUTPUT_HANDLE),msg, sizeof(msg)-1, 
      &written,NULL);
  }
  /*
    Return EXCEPTION_CONTINUE_SEARCH to give JIT debugger
    (drwtsn32 or vsjitdebugger) possibility to attach,
    if JIT debugger is configured.
    Windows Error reporting might generate a dump here.
  */
  return EXCEPTION_CONTINUE_SEARCH;
}


unknown's avatar
unknown committed
2357 2358
static void init_signals(void)
{
2359 2360
  if(opt_console)
    SetConsoleCtrlHandler(console_event_handler,TRUE);
2361

2362
    /* Avoid MessageBox()es*/
2363 2364 2365 2366 2367 2368
  _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
  _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
  _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
  _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
  _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
2369 2370 2371 2372 2373 2374 2375 2376

   /*
     Do not use SEM_NOGPFAULTERRORBOX in the following SetErrorMode (),
     because it would prevent JIT debugger and Windows error reporting
     from working. We need WER or JIT-debugging, since our own unhandled
     exception filter is not guaranteed to work in all situation
     (like heap corruption or stack overflow)
   */
2377 2378
  SetErrorMode(SetErrorMode(0) | SEM_FAILCRITICALERRORS
                               | SEM_NOOPENFILEERRORBOX);
2379
  SetUnhandledExceptionFilter(my_unhandler_exception_filter);
unknown's avatar
unknown committed
2380 2381
}

unknown's avatar
unknown committed
2382

2383
static void start_signal_handler(void)
2384
{
2385
#ifndef EMBEDDED_LIBRARY
2386 2387 2388
  // Save vm id of this process
  if (!opt_bootstrap)
    create_pid_file();
2389
#endif /* EMBEDDED_LIBRARY */
2390
}
unknown's avatar
unknown committed
2391

unknown's avatar
unknown committed
2392

unknown's avatar
unknown committed
2393 2394
static void check_data_home(const char *path)
{}
2395

unknown's avatar
unknown committed
2396

unknown's avatar
unknown committed
2397 2398
#elif defined(__NETWARE__)

unknown's avatar
unknown committed
2399
/// down server event callback.
unknown's avatar
unknown committed
2400 2401
void mysql_down_server_cb(void *, void *)
{
unknown's avatar
Merge  
unknown committed
2402
  event_flag= TRUE;
unknown's avatar
unknown committed
2403 2404 2405
  kill_server(0);
}

unknown's avatar
unknown committed
2406

unknown's avatar
unknown committed
2407
/// destroy callback resources.
unknown's avatar
unknown committed
2408
void mysql_cb_destroy(void *)
unknown's avatar
Merge  
unknown committed
2409 2410
{
  UnRegisterEventNotification(eh);  // cleanup down event notification
unknown's avatar
unknown committed
2411
  NX_UNWRAP_INTERFACE(ref);
unknown's avatar
Merge  
unknown committed
2412 2413
  /* Deregister NSS volume deactivation event */
  NX_UNWRAP_INTERFACE(refneb);
unknown's avatar
unknown committed
2414
  if (neb_consumer_id)
2415
    UnRegisterConsumer(neb_consumer_id, NULL);
unknown's avatar
unknown committed
2416 2417
}

unknown's avatar
unknown committed
2418

unknown's avatar
unknown committed
2419
/// initialize callbacks.
unknown's avatar
unknown committed
2420 2421 2422 2423
void mysql_cb_init()
{
  // register for down server event
  void *handle = getnlmhandle();
unknown's avatar
unknown committed
2424 2425
  rtag_t rt= AllocateResourceTag(handle, "MySQL Down Server Callback",
                                 EventSignature);
unknown's avatar
unknown committed
2426
  NX_WRAP_INTERFACE((void *)mysql_down_server_cb, 2, (void **)&ref);
unknown's avatar
unknown committed
2427 2428 2429 2430 2431 2432 2433 2434
  eh= RegisterForEventNotification(rt, EVENT_PRE_DOWN_SERVER,
                                   EVENT_PRIORITY_APPLICATION,
                                   NULL, ref, NULL);

  /*
    Register for volume deactivation event
    Wrap the callback function, as it is called by non-LibC thread
  */
2435
  (void *) NX_WRAP_INTERFACE(neb_event_callback, 1, &refneb);
unknown's avatar
unknown committed
2436 2437
  registerwithneb();

unknown's avatar
unknown committed
2438 2439 2440
  NXVmRegisterExitHandler(mysql_cb_destroy, NULL);  // clean-up
}

unknown's avatar
unknown committed
2441

unknown's avatar
unknown committed
2442
/** To get the name of the NetWare volume having MySQL data folder. */
2443
static void getvolumename()
unknown's avatar
unknown committed
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
{
  char *p;
  /*
    We assume that data path is already set.
    If not it won't come here. Terminate after volume name
  */
  if ((p= strchr(mysql_real_data_home, ':')))
    strmake(datavolname, mysql_real_data_home,
            (uint) (p - mysql_real_data_home));
}


unknown's avatar
unknown committed
2456 2457
/**
  Registering with NEB for NSS Volume Deactivation event.
unknown's avatar
unknown committed
2458 2459
*/

2460
static void registerwithneb()
unknown's avatar
unknown committed
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508
{

  ConsumerRegistrationInfo reg_info;
    
  /* Clear NEB registration structure */
  bzero((char*) &reg_info, sizeof(struct ConsumerRegistrationInfo));

  /* Fill the NEB consumer information structure */
  reg_info.CRIVersion= 1;  	            // NEB version
  /* NEB Consumer name */
  reg_info.CRIConsumerName= (BYTE *) "MySQL Database Server";
  /* Event of interest */
  reg_info.CRIEventName= (BYTE *) "NSS.ChangeVolState.Enter";
  reg_info.CRIUserParameter= NULL;	    // Consumer Info
  reg_info.CRIEventFlags= 0;	            // Event flags
  /* Consumer NLM handle */
  reg_info.CRIOwnerID= (LoadDefinitionStructure *)getnlmhandle();
  reg_info.CRIConsumerESR= NULL;	    // No consumer ESR required
  reg_info.CRISecurityToken= 0;	            // No security token for the event
  reg_info.CRIConsumerFlags= 0;             // SMP_ENABLED_BIT;	
  reg_info.CRIFilterName= 0;	            // No event filtering
  reg_info.CRIFilterDataLength= 0;          // No filtering data
  reg_info.CRIFilterData= 0;	            // No filtering data
  /* Callback function for the event */
  (void *)reg_info.CRIConsumerCallback= (void *) refneb;
  reg_info.CRIOrder= 0;	                    // Event callback order
  reg_info.CRIConsumerType= CHECK_CONSUMER; // Consumer type

  /* Register for the event with NEB */
  if (RegisterConsumer(&reg_info))
  {
    consoleprintf("Failed to register for NSS Volume Deactivation event \n");
    return;
  }
  /* This ID is required for deregistration */
  neb_consumer_id= reg_info.CRIConsumerID;

  /* Get MySQL data volume name, stored in global variable datavolname */
  getvolumename();

  /*
    Get the NSS volume ID of the MySQL Data volume.
    Volume ID is stored in a global variable
  */
  getvolumeID((BYTE*) datavolname);	
}


unknown's avatar
unknown committed
2509 2510
/**
  Callback for NSS Volume Deactivation event.
unknown's avatar
unknown committed
2511
*/
2512

unknown's avatar
unknown committed
2513 2514 2515
ulong neb_event_callback(struct EventBlock *eblock)
{
  EventChangeVolStateEnter_s *voldata;
2516 2517
  extern bool nw_panic;

unknown's avatar
unknown committed
2518 2519 2520
  voldata= (EventChangeVolStateEnter_s *)eblock->EBEventData;

  /* Deactivation of a volume */
unknown's avatar
unknown committed
2521 2522 2523
  if ((voldata->oldState == zVOLSTATE_ACTIVE &&
       voldata->newState == zVOLSTATE_DEACTIVE ||
       voldata->newState == zVOLSTATE_MAINTENANCE))
unknown's avatar
unknown committed
2524 2525 2526 2527 2528 2529 2530 2531
  {
    /*
      Ensure that we bring down MySQL server only for MySQL data
      volume deactivation
    */
    if (!memcmp(&voldata->volID, &datavolid, sizeof(VolumeID_t)))
    {
      consoleprintf("MySQL data volume is deactivated, shutting down MySQL Server \n");
unknown's avatar
unknown committed
2532
      event_flag= TRUE;
2533
      nw_panic = TRUE;
2534
      event_flag= TRUE;
unknown's avatar
unknown committed
2535 2536 2537 2538 2539 2540 2541 2542 2543
      kill_server(0);
    }
  }
  return 0;
}


#define ADMIN_VOL_PATH					"_ADMIN:/Volumes/"

unknown's avatar
unknown committed
2544 2545 2546
/**
  Function to get NSS volume ID of the MySQL data.
*/
2547
static void getvolumeID(BYTE *volumeName)
unknown's avatar
unknown committed
2548 2549 2550 2551 2552 2553 2554
{
  char path[zMAX_FULL_NAME];
  Key_t rootKey= 0, fileKey= 0;
  QUAD getInfoMask;
  zInfo_s info;
  STATUS status;

2555
  /* Get the root key */
unknown's avatar
unknown committed
2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
  if ((status= zRootKey(0, &rootKey)) != zOK)
  {
    consoleprintf("\nGetNSSVolumeProperties - Failed to get root key, status: %d\n.", (int) status);
    goto exit;
  }

  /*
    Get the file key. This is the key to the volume object in the
    NSS admin volumes directory.
  */

  strxmov(path, (const char *) ADMIN_VOL_PATH, (const char *) volumeName,
          NullS);
  if ((status= zOpen(rootKey, zNSS_TASK, zNSPACE_LONG|zMODE_UTF8, 
                     (BYTE *) path, zRR_READ_ACCESS, &fileKey)) != zOK)
  {
    consoleprintf("\nGetNSSVolumeProperties - Failed to get file, status: %d\n.", (int) status);
    goto exit;
  }

  getInfoMask= zGET_IDS | zGET_VOLUME_INFO ;
  if ((status= zGetInfo(fileKey, getInfoMask, sizeof(info), 
                        zINFO_VERSION_A, &info)) != zOK)
  {
    consoleprintf("\nGetNSSVolumeProperties - Failed in zGetInfo, status: %d\n.", (int) status);
    goto exit;
  }

  /* Copy the data to global variable */
  datavolid.timeLow= info.vol.volumeID.timeLow;
  datavolid.timeMid= info.vol.volumeID.timeMid;
  datavolid.timeHighAndVersion= info.vol.volumeID.timeHighAndVersion;
  datavolid.clockSeqHighAndReserved= info.vol.volumeID.clockSeqHighAndReserved;
  datavolid.clockSeqLow= info.vol.volumeID.clockSeqLow;
  /* This is guranteed to be 6-byte length (but sizeof() would be better) */
  memcpy(datavolid.node, info.vol.volumeID.node, (unsigned int) 6);
unknown's avatar
Merge  
unknown committed
2592

unknown's avatar
unknown committed
2593 2594 2595 2596 2597 2598 2599 2600
exit:
  if (rootKey)
    zClose(rootKey);
  if (fileKey)
    zClose(fileKey);
}


unknown's avatar
unknown committed
2601 2602 2603 2604 2605 2606 2607 2608
static void init_signals(void)
{
  int signals[] = {SIGINT,SIGILL,SIGFPE,SIGSEGV,SIGTERM,SIGABRT};

  for (uint i=0 ; i < sizeof(signals)/sizeof(int) ; i++)
    signal(signals[i], kill_server);
  mysql_cb_init();  // initialize callbacks

2609
}
unknown's avatar
unknown committed
2610

2611

unknown's avatar
unknown committed
2612 2613 2614 2615
static void start_signal_handler(void)
{
  // Save vm id of this process
  if (!opt_bootstrap)
2616
    create_pid_file();
unknown's avatar
unknown committed
2617 2618 2619 2620
  // no signal handler
}


unknown's avatar
unknown committed
2621 2622
/**
  Warn if the data is on a Traditional volume.
unknown's avatar
unknown committed
2623

unknown's avatar
unknown committed
2624
  @note
unknown's avatar
unknown committed
2625 2626
    Already done by mysqld_safe
*/
unknown's avatar
unknown committed
2627 2628

static void check_data_home(const char *path)
2629 2630 2631
{
}

2632
#endif /*__WIN__ || __NETWARE */
unknown's avatar
unknown committed
2633

unknown's avatar
unknown committed
2634 2635
#ifdef HAVE_LINUXTHREADS
#define UNSAFE_DEFAULT_LINUX_THREADS 200
2636
#endif
2637

unknown's avatar
unknown committed
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647

#if BACKTRACE_DEMANGLE
#include <cxxabi.h>
extern "C" char *my_demangle(const char *mangled_name, int *status)
{
  return abi::__cxa_demangle(mangled_name, NULL, NULL, status);
}
#endif


2648
extern "C" sig_handler handle_segfault(int sig)
2649
{
2650 2651
  time_t curr_time;
  struct tm tm;
unknown's avatar
unknown committed
2652
  THD *thd=current_thd;
2653

2654 2655 2656 2657 2658 2659
  /*
    Strictly speaking, one needs a mutex here
    but since we have got SIGSEGV already, things are a mess
    so not having the mutex is not as bad as possibly using a buggy
    mutex - so we keep things simple
  */
2660
  if (segfaulted)
unknown's avatar
unknown committed
2661
  {
2662
    fprintf(stderr, "Fatal " SIGNAL_FMT " while backtracing\n", sig);
unknown's avatar
unknown committed
2663 2664
    exit(1);
  }
2665

2666
  segfaulted = 1;
2667

2668
  curr_time= my_time(0);
2669 2670
  localtime_r(&curr_time, &tm);

2671
  fprintf(stderr,"\
2672
%02d%02d%02d %2d:%02d:%02d - mysqld got " SIGNAL_FMT " ;\n\
unknown's avatar
unknown committed
2673
This could be because you hit a bug. It is also possible that this binary\n\
unknown's avatar
unknown committed
2674
or one of the libraries it was linked against is corrupt, improperly built,\n\
unknown's avatar
unknown committed
2675
or misconfigured. This error can also be caused by malfunctioning hardware.\n",
2676 2677
          tm.tm_year % 100, tm.tm_mon+1, tm.tm_mday,
          tm.tm_hour, tm.tm_min, tm.tm_sec,
unknown's avatar
unknown committed
2678 2679 2680 2681
	  sig);
  fprintf(stderr, "\
We will try our best to scrape up some info that will hopefully help diagnose\n\
the problem, but since we have already crashed, something is definitely wrong\n\
unknown's avatar
unknown committed
2682
and this may fail.\n\n");
2683
  fprintf(stderr, "key_buffer_size=%lu\n",
unknown's avatar
unknown committed
2684
          (ulong) dflt_key_cache->key_cache_mem_size);
unknown's avatar
unknown committed
2685 2686
  fprintf(stderr, "read_buffer_size=%ld\n", (long) global_system_variables.read_buff_size);
  fprintf(stderr, "max_used_connections=%lu\n", max_used_connections);
unknown's avatar
unknown committed
2687
  fprintf(stderr, "max_threads=%u\n", thread_scheduler.max_threads);
Konstantin Osipov's avatar
Konstantin Osipov committed
2688 2689
  fprintf(stderr, "thread_count=%u\n", thread_count);
  fprintf(stderr, "connection_count=%u\n", connection_count);
unknown's avatar
unknown committed
2690
  fprintf(stderr, "It is possible that mysqld could use up to \n\
unknown's avatar
unknown committed
2691
key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = %lu K\n\
unknown's avatar
unknown committed
2692
bytes of memory\n", ((ulong) dflt_key_cache->key_cache_mem_size +
2693
		     (global_system_variables.read_buff_size +
unknown's avatar
unknown committed
2694
		      global_system_variables.sortbuff_size) *
unknown's avatar
unknown committed
2695 2696
		     thread_scheduler.max_threads +
                     max_connections * sizeof(THD)) / 1024);
unknown's avatar
unknown committed
2697
  fprintf(stderr, "Hope that's ok; if not, decrease some variables in the equation.\n\n");
2698

2699
#if defined(HAVE_LINUXTHREADS)
unknown's avatar
unknown committed
2700 2701 2702 2703
  if (sizeof(char*) == 4 && thread_count > UNSAFE_DEFAULT_LINUX_THREADS)
  {
    fprintf(stderr, "\
You seem to be running 32-bit Linux and have %d concurrent connections.\n\
unknown's avatar
unknown committed
2704 2705
If you have not changed STACK_SIZE in LinuxThreads and built the binary \n\
yourself, LinuxThreads is quite likely to steal a part of the global heap for\n\
unknown's avatar
unknown committed
2706
the thread stack. Please read http://dev.mysql.com/doc/mysql/en/linux.html\n\n",
unknown's avatar
unknown committed
2707 2708 2709
	    thread_count);
  }
#endif /* HAVE_LINUXTHREADS */
unknown's avatar
unknown committed
2710

unknown's avatar
unknown committed
2711
#ifdef HAVE_STACKTRACE
2712
  if (!(test_flags & TEST_NO_STACKTRACE))
unknown's avatar
unknown committed
2713
  {
unknown's avatar
unknown committed
2714
    fprintf(stderr,"thd: 0x%lx\n",(long) thd);
2715 2716 2717
    fprintf(stderr,"\
Attempting backtrace. You can use the following information to find out\n\
where mysqld died. If you see no messages after this, something went\n\
2718
terribly wrong...\n");  
2719 2720
    my_print_stacktrace(thd ? (uchar*) thd->thread_stack : NULL,
                        my_thread_stack_size);
unknown's avatar
unknown committed
2721
  }
unknown's avatar
unknown committed
2722 2723
  if (thd)
  {
unknown's avatar
unknown committed
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
    const char *kreason= "UNKNOWN";
    switch (thd->killed) {
    case THD::NOT_KILLED:
      kreason= "NOT_KILLED";
      break;
    case THD::KILL_BAD_DATA:
      kreason= "KILL_BAD_DATA";
      break;
    case THD::KILL_CONNECTION:
      kreason= "KILL_CONNECTION";
      break;
    case THD::KILL_QUERY:
      kreason= "KILL_QUERY";
      break;
    case THD::KILLED_NO_VALUE:
      kreason= "KILLED_NO_VALUE";
      break;
    }
unknown's avatar
unknown committed
2742 2743
    fprintf(stderr, "Trying to get some variables.\n\
Some pointers may be invalid and cause the dump to abort...\n");
2744
    my_safe_print_str("thd->query", thd->query(), 1024);
unknown's avatar
unknown committed
2745
    fprintf(stderr, "thd->thread_id=%lu\n", (ulong) thd->thread_id);
unknown's avatar
unknown committed
2746
    fprintf(stderr, "thd->killed=%s\n", kreason);
unknown's avatar
unknown committed
2747 2748
  }
  fprintf(stderr, "\
unknown's avatar
unknown committed
2749
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains\n\
unknown's avatar
unknown committed
2750
information that should help you find out what is causing the crash.\n");
2751
  fflush(stderr);
unknown's avatar
unknown committed
2752 2753
#endif /* HAVE_STACKTRACE */

2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
#ifdef HAVE_INITGROUPS
  if (calling_initgroups)
    fprintf(stderr, "\n\
This crash occured while the server was calling initgroups(). This is\n\
often due to the use of a mysqld that is statically linked against glibc\n\
and configured to use LDAP in /etc/nsswitch.conf. You will need to either\n\
upgrade to a version of glibc that does not have this problem (2.3.4 or\n\
later when used with nscd), disable LDAP in your nsswitch.conf, or use a\n\
mysqld that is not statically linked.\n");
#endif

2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
#ifdef HAVE_NPTL
  if (thd_lib_detected == THD_LIB_LT && !getenv("LD_ASSUME_KERNEL"))
    fprintf(stderr,"\n\
You are running a statically-linked LinuxThreads binary on an NPTL system.\n\
This can result in crashes on some distributions due to LT/NPTL conflicts.\n\
You should either build a dynamically-linked binary, or force LinuxThreads\n\
to be used with the LD_ASSUME_KERNEL environment variable. Please consult\n\
the documentation for your distribution on how to do that.\n");
#endif
  
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
  if (locked_in_memory)
  {
    fprintf(stderr, "\n\
The \"--memlock\" argument, which was enabled, uses system calls that are\n\
unreliable and unstable on some operating systems and operating-system\n\
versions (notably, some versions of Linux).  This crash could be due to use\n\
of those buggy OS calls.  You should consider whether you really need the\n\
\"--memlock\" parameter and/or consult the OS distributer about \"mlockall\"\n\
bugs.\n");
  }

2786
#ifdef HAVE_WRITE_CORE
2787 2788 2789 2790
  if (test_flags & TEST_CORE_ON_SIGNAL)
  {
    fprintf(stderr, "Writing a core file\n");
    fflush(stderr);
2791
    my_write_core(sig);
2792
  }
2793 2794 2795 2796
#endif

#ifndef __WIN__
  /* On Windows, do not terminate, but pass control to exception filter */
2797
  exit(1);
2798
#endif
2799 2800
}

2801
#if !defined(__WIN__) && !defined(__NETWARE__)
unknown's avatar
unknown committed
2802 2803 2804 2805 2806 2807
#ifndef SA_RESETHAND
#define SA_RESETHAND 0
#endif
#ifndef SA_NODEFER
#define SA_NODEFER 0
#endif
2808

2809 2810
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
2811 2812 2813
static void init_signals(void)
{
  sigset_t set;
2814
  struct sigaction sa;
unknown's avatar
unknown committed
2815 2816
  DBUG_ENTER("init_signals");

2817
  my_sigset(THR_SERVER_ALARM,print_signal_warning); // Should never be called!
unknown's avatar
unknown committed
2818

unknown's avatar
unknown committed
2819
  if (!(test_flags & TEST_NO_STACKTRACE) || (test_flags & TEST_CORE_ON_SIGNAL))
unknown's avatar
unknown committed
2820
  {
unknown's avatar
unknown committed
2821 2822 2823 2824
    sa.sa_flags = SA_RESETHAND | SA_NODEFER;
    sigemptyset(&sa.sa_mask);
    sigprocmask(SIG_SETMASK,&sa.sa_mask,NULL);

2825
#ifdef HAVE_STACKTRACE
2826
    my_init_stacktrace();
2827
#endif
unknown's avatar
unknown committed
2828 2829 2830
#if defined(__amiga__)
    sa.sa_handler=(void(*)())handle_segfault;
#else
unknown's avatar
unknown committed
2831
    sa.sa_handler=handle_segfault;
unknown's avatar
unknown committed
2832
#endif
unknown's avatar
unknown committed
2833
    sigaction(SIGSEGV, &sa, NULL);
2834
    sigaction(SIGABRT, &sa, NULL);
unknown's avatar
unknown committed
2835
#ifdef SIGBUS
unknown's avatar
unknown committed
2836
    sigaction(SIGBUS, &sa, NULL);
unknown's avatar
unknown committed
2837
#endif
unknown's avatar
unknown committed
2838
    sigaction(SIGILL, &sa, NULL);
2839
    sigaction(SIGFPE, &sa, NULL);
unknown's avatar
unknown committed
2840
  }
2841 2842 2843 2844 2845

#ifdef HAVE_GETRLIMIT
  if (test_flags & TEST_CORE_ON_SIGNAL)
  {
    /* Change limits so that we will get a core file */
2846
    STRUCT_RLIMIT rl;
2847
    rl.rlim_cur = rl.rlim_max = RLIM_INFINITY;
unknown's avatar
unknown committed
2848
    if (setrlimit(RLIMIT_CORE, &rl) && global_system_variables.log_warnings)
2849
      sql_print_warning("setrlimit could not change the size of core files to 'infinity';  We may not be able to generate a core file on signals");
2850 2851
  }
#endif
unknown's avatar
unknown committed
2852
  (void) sigemptyset(&set);
2853
  my_sigset(SIGPIPE,SIG_IGN);
unknown's avatar
unknown committed
2854
  sigaddset(&set,SIGPIPE);
2855
#ifndef IGNORE_SIGHUP_SIGQUIT
unknown's avatar
unknown committed
2856 2857
  sigaddset(&set,SIGQUIT);
  sigaddset(&set,SIGHUP);
2858 2859
#endif
  sigaddset(&set,SIGTERM);
2860 2861

  /* Fix signals if blocked by parents (can happen on Mac OS X) */
unknown's avatar
unknown committed
2862
  sigemptyset(&sa.sa_mask);
2863 2864 2865 2866 2867 2868
  sa.sa_flags = 0;
  sa.sa_handler = print_signal_warning;
  sigaction(SIGTERM, &sa, (struct sigaction*) 0);
  sa.sa_flags = 0;
  sa.sa_handler = print_signal_warning;
  sigaction(SIGHUP, &sa, (struct sigaction*) 0);
unknown's avatar
unknown committed
2869 2870 2871
#ifdef SIGTSTP
  sigaddset(&set,SIGTSTP);
#endif
2872 2873
  if (thd_lib_detected != THD_LIB_LT)
    sigaddset(&set,THR_SERVER_ALARM);
2874
  if (test_flags & TEST_SIGINT)
2875
  {
2876
    my_sigset(thr_kill_signal, end_thread_signal);
2877 2878 2879
    // May be SIGINT
    sigdelset(&set, thr_kill_signal);
  }
2880 2881
  else
    sigaddset(&set,SIGINT);
2882 2883
  sigprocmask(SIG_SETMASK,&set,NULL);
  pthread_sigmask(SIG_SETMASK,&set,NULL);
2884 2885 2886 2887 2888 2889 2890 2891 2892
  DBUG_VOID_RETURN;
}


static void start_signal_handler(void)
{
  int error;
  pthread_attr_t thr_attr;
  DBUG_ENTER("start_signal_handler");
unknown's avatar
unknown committed
2893 2894 2895 2896 2897

  (void) pthread_attr_init(&thr_attr);
#if !defined(HAVE_DEC_3_2_THREADS)
  pthread_attr_setscope(&thr_attr,PTHREAD_SCOPE_SYSTEM);
  (void) pthread_attr_setdetachstate(&thr_attr,PTHREAD_CREATE_DETACHED);
2898
#if defined(__ia64__) || defined(__ia64)
2899 2900 2901 2902
  /*
    Peculiar things with ia64 platforms - it seems we only have half the
    stack size in reality, so we have to double it here
  */
2903
  pthread_attr_setstacksize(&thr_attr,my_thread_stack_size*2);
2904
#else
2905
  pthread_attr_setstacksize(&thr_attr,my_thread_stack_size);
2906
#endif
unknown's avatar
unknown committed
2907 2908
#endif

Marc Alff's avatar
Marc Alff committed
2909
  mysql_mutex_lock(&LOCK_thread_count);
Marc Alff's avatar
Marc Alff committed
2910 2911
  if ((error= mysql_thread_create(key_thread_signal_hand,
                                  &signal_thread, &thr_attr, signal_hand, 0)))
unknown's avatar
unknown committed
2912 2913 2914 2915 2916
  {
    sql_print_error("Can't create interrupt-thread (error %d, errno: %d)",
		    error,errno);
    exit(1);
  }
Marc Alff's avatar
Marc Alff committed
2917 2918
  mysql_cond_wait(&COND_thread_count, &LOCK_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
2919 2920 2921 2922 2923 2924

  (void) pthread_attr_destroy(&thr_attr);
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
2925
/** This threads handles all signals and alarms. */
unknown's avatar
unknown committed
2926
/* ARGSUSED */
2927
pthread_handler_t signal_hand(void *arg __attribute__((unused)))
unknown's avatar
unknown committed
2928 2929 2930 2931 2932
{
  sigset_t set;
  int sig;
  my_thread_init();				// Init new thread
  DBUG_ENTER("signal_hand");
unknown's avatar
unknown committed
2933 2934
  signal_thread_in_use= 1;

unknown's avatar
unknown committed
2935 2936
  /*
    Setup alarm handler
2937 2938
    This should actually be '+ max_number_of_slaves' instead of +10,
    but the +10 should be quite safe.
unknown's avatar
unknown committed
2939
  */
unknown's avatar
unknown committed
2940
  init_thr_alarm(thread_scheduler.max_threads +
2941
		 global_system_variables.max_insert_delayed_threads + 10);
2942
  if (thd_lib_detected != THD_LIB_LT && (test_flags & TEST_SIGINT))
2943 2944 2945 2946 2947
  {
    (void) sigemptyset(&set);			// Setup up SIGINT for debug
    (void) sigaddset(&set,SIGINT);		// For debugging
    (void) pthread_sigmask(SIG_UNBLOCK,&set,NULL);
  }
unknown's avatar
unknown committed
2948 2949 2950 2951
  (void) sigemptyset(&set);			// Setup up SIGINT for debug
#ifdef USE_ONE_SIGNAL_HAND
  (void) sigaddset(&set,THR_SERVER_ALARM);	// For alarms
#endif
2952
#ifndef IGNORE_SIGHUP_SIGQUIT
unknown's avatar
unknown committed
2953 2954
  (void) sigaddset(&set,SIGQUIT);
  (void) sigaddset(&set,SIGHUP);
2955 2956
#endif
  (void) sigaddset(&set,SIGTERM);
unknown's avatar
unknown committed
2957 2958 2959
  (void) sigaddset(&set,SIGTSTP);

  /* Save pid to this process (or thread on Linux) */
2960
  if (!opt_bootstrap)
2961 2962
    create_pid_file();

2963 2964 2965 2966 2967 2968 2969
#ifdef HAVE_STACK_TRACE_ON_SEGV
  if (opt_do_pstack)
  {
    sprintf(pstack_file_name,"mysqld-%lu-%%d-%%d.backtrace", (ulong)getpid());
    pstack_install_segv_action(pstack_file_name);
  }
#endif /* HAVE_STACK_TRACE_ON_SEGV */
unknown's avatar
unknown committed
2970

2971 2972 2973 2974 2975
  /*
    signal to start_signal_handler that we are ready
    This works by waiting for start_signal_handler to free mutex,
    after which we signal it that we are ready.
    At this pointer there is no other threads running, so there
Marc Alff's avatar
Marc Alff committed
2976
    should not be any other mysql_cond_signal() calls.
2977
  */
Marc Alff's avatar
Marc Alff committed
2978 2979 2980
  mysql_mutex_lock(&LOCK_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);
  mysql_cond_broadcast(&COND_thread_count);
unknown's avatar
unknown committed
2981

2982
  (void) pthread_sigmask(SIG_BLOCK,&set,NULL);
unknown's avatar
unknown committed
2983 2984 2985 2986 2987
  for (;;)
  {
    int error;					// Used when debugging
    if (shutdown_in_progress && !abort_loop)
    {
2988
      sig= SIGTERM;
unknown's avatar
unknown committed
2989 2990 2991 2992 2993
      error=0;
    }
    else
      while ((error=my_sigwait(&set,&sig)) == EINTR) ;
    if (cleanup_done)
2994
    {
2995
      DBUG_PRINT("quit",("signal_handler: calling my_thread_end()"));
2996
      my_thread_end();
unknown's avatar
unknown committed
2997
      signal_thread_in_use= 0;
2998
      DBUG_LEAVE;                               // Must match DBUG_ENTER()
unknown's avatar
unknown committed
2999
      pthread_exit(0);				// Safety
3000
      return 0;                                 // Avoid compiler warnings
3001
    }
unknown's avatar
unknown committed
3002 3003 3004 3005 3006
    switch (sig) {
    case SIGTERM:
    case SIGQUIT:
    case SIGKILL:
#ifdef EXTRA_DEBUG
3007
      sql_print_information("Got signal %d to shutdown mysqld",sig);
unknown's avatar
unknown committed
3008
#endif
3009
      /* switch to the old log message processing */
3010 3011
      logger.set_handlers(LOG_FILE, opt_slow_log ? LOG_FILE:LOG_NONE,
                          opt_log ? LOG_FILE:LOG_NONE);
unknown's avatar
unknown committed
3012 3013 3014 3015 3016 3017
      DBUG_PRINT("info",("Got signal: %d  abort_loop: %d",sig,abort_loop));
      if (!abort_loop)
      {
	abort_loop=1;				// mark abort for threads
#ifdef USE_ONE_SIGNAL_HAND
	pthread_t tmp;
Marc Alff's avatar
Marc Alff committed
3018 3019 3020
        if (mysql_thread_create(0, /* Not instrumented */
                                &tmp, &connection_attrib, kill_server_thread,
                                (void*) &sig))
3021
	  sql_print_error("Can't create thread to kill server");
unknown's avatar
unknown committed
3022
#else
unknown's avatar
unknown committed
3023
	kill_server((void*) sig);	// MIT THREAD has a alarm thread
unknown's avatar
unknown committed
3024 3025 3026 3027
#endif
      }
      break;
    case SIGHUP:
unknown's avatar
unknown committed
3028 3029
      if (!abort_loop)
      {
unknown's avatar
unknown committed
3030
        bool not_used;
unknown's avatar
Merge  
unknown committed
3031
	mysql_print_status();		// Print some debug info
unknown's avatar
unknown committed
3032 3033
	reload_acl_and_cache((THD*) 0,
			     (REFRESH_LOG | REFRESH_TABLES | REFRESH_FAST |
unknown's avatar
Merge  
unknown committed
3034
			      REFRESH_GRANT |
unknown's avatar
unknown committed
3035
			      REFRESH_THREADS | REFRESH_HOSTS),
unknown's avatar
unknown committed
3036
			     (TABLE_LIST*) 0, &not_used); // Flush logs
unknown's avatar
unknown committed
3037
      }
3038
      /* reenable logs after the options were reloaded */
3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050
      if (log_output_options & LOG_NONE)
      {
        logger.set_handlers(LOG_FILE,
                            opt_slow_log ? LOG_TABLE : LOG_NONE,
                            opt_log ? LOG_TABLE : LOG_NONE);
      }
      else
      {
        logger.set_handlers(LOG_FILE,
                            opt_slow_log ? log_output_options : LOG_NONE,
                            opt_log ? log_output_options : LOG_NONE);
      }
unknown's avatar
unknown committed
3051 3052 3053 3054 3055 3056 3057 3058
      break;
#ifdef USE_ONE_SIGNAL_HAND
    case THR_SERVER_ALARM:
      process_alarm(sig);			// Trigger alarms.
      break;
#endif
    default:
#ifdef EXTRA_DEBUG
3059
      sql_print_warning("Got signal: %d  error: %d",sig,error); /* purecov: tested */
unknown's avatar
unknown committed
3060 3061 3062 3063 3064 3065 3066
#endif
      break;					/* purecov: tested */
    }
  }
  return(0);					/* purecov: deadcode */
}

unknown's avatar
unknown committed
3067
static void check_data_home(const char *path)
unknown's avatar
unknown committed
3068
{}
unknown's avatar
unknown committed
3069

3070
#endif /*!EMBEDDED_LIBRARY*/
unknown's avatar
unknown committed
3071 3072 3073
#endif	/* __WIN__*/


unknown's avatar
unknown committed
3074
/**
unknown's avatar
Merge  
unknown committed
3075
  All global error messages are sent here where the first one is stored
unknown's avatar
unknown committed
3076
  for the client.
unknown's avatar
unknown committed
3077 3078
*/
/* ARGSUSED */
Marc Alff's avatar
Marc Alff committed
3079
extern "C" void my_message_sql(uint error, const char *str, myf MyFlags);
3080

Marc Alff's avatar
Marc Alff committed
3081
void my_message_sql(uint error, const char *str, myf MyFlags)
unknown's avatar
unknown committed
3082
{
Marc Alff's avatar
Marc Alff committed
3083
  THD *thd= current_thd;
unknown's avatar
unknown committed
3084
  DBUG_ENTER("my_message_sql");
unknown's avatar
Merge  
unknown committed
3085
  DBUG_PRINT("error", ("error: %u  message: '%s'", error, str));
3086 3087

  DBUG_ASSERT(str != NULL);
unknown's avatar
Merge  
unknown committed
3088
  /*
3089 3090 3091 3092 3093 3094
    An error should have a valid error number (!= 0), so it can be caught
    in stored procedures by SQL exception handlers.
    Calling my_error() with error == 0 is a bug.
    Remaining known places to fix:
    - storage/myisam/mi_create.c, my_printf_error()
    TODO:
unknown's avatar
Merge  
unknown committed
3095 3096
    DBUG_ASSERT(error != 0);
  */
3097 3098 3099 3100 3101 3102 3103 3104

  if (error == 0)
  {
    /* At least, prevent new abuse ... */
    DBUG_ASSERT(strncmp(str, "MyISAM table", 12) == 0);
    error= ER_UNKNOWN_ERROR;
  }

3105 3106
  mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_ERROR, error, str);

Marc Alff's avatar
Marc Alff committed
3107
  if (thd)
unknown's avatar
unknown committed
3108
  {
Marc Alff's avatar
Marc Alff committed
3109 3110 3111 3112 3113 3114
    if (MyFlags & ME_FATALERROR)
      thd->is_fatal_error= 1;
    (void) thd->raise_condition(error,
                                NULL,
                                MYSQL_ERROR::WARN_LEVEL_ERROR,
                                str);
unknown's avatar
unknown committed
3115
  }
3116 3117

  /* When simulating OOM, skip writing to error log to avoid mtr errors */
3118
  DBUG_EXECUTE_IF("simulate_out_of_memory", DBUG_VOID_RETURN;);
3119

unknown's avatar
unknown committed
3120
  if (!thd || MyFlags & ME_NOREFRESH)
unknown's avatar
unknown committed
3121
    sql_print_error("%s: %s",my_progname,str); /* purecov: inspected */
Marc Alff's avatar
Marc Alff committed
3122
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
3123 3124
}

3125

3126
#ifndef EMBEDDED_LIBRARY
3127 3128 3129 3130
extern "C" void *my_str_malloc_mysqld(size_t size);
extern "C" void my_str_free_mysqld(void *ptr);

void *my_str_malloc_mysqld(size_t size)
3131 3132 3133 3134 3135
{
  return my_malloc(size, MYF(MY_FAE));
}


3136
void my_str_free_mysqld(void *ptr)
3137
{
3138
  my_free(ptr, MYF(MY_FAE));
3139
}
3140
#endif /* EMBEDDED_LIBRARY */
3141 3142


unknown's avatar
unknown committed
3143 3144
#ifdef __WIN__

3145
pthread_handler_t handle_shutdown(void *arg)
unknown's avatar
unknown committed
3146 3147 3148 3149 3150 3151
{
  MSG msg;
  my_thread_init();

  /* this call should create the message queue for this thread */
  PeekMessage(&msg, NULL, 1, 65534,PM_NOREMOVE);
unknown's avatar
unknown committed
3152
#if !defined(EMBEDDED_LIBRARY)
unknown's avatar
unknown committed
3153
  if (WaitForSingleObject(hEventShutdown,INFINITE)==WAIT_OBJECT_0)
3154
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
3155 3156 3157 3158 3159
     kill_server(MYSQL_KILL_SIGNAL);
  return 0;
}
#endif

3160
const char *load_default_groups[]= {
3161
#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE
3162 3163
"mysql_cluster",
#endif
unknown's avatar
Merge  
unknown committed
3164 3165
"mysqld","server", MYSQL_BASE_VERSION, 0, 0};

3166
#if defined(__WIN__) && !defined(EMBEDDED_LIBRARY)
3167 3168
static const int load_default_groups_sz=
sizeof(load_default_groups)/sizeof(load_default_groups[0]);
unknown's avatar
Merge  
unknown committed
3169
#endif
unknown's avatar
unknown committed
3170

unknown's avatar
unknown committed
3171

unknown's avatar
unknown committed
3172 3173
/**
  Initialize one of the global date/time format variables.
3174

unknown's avatar
unknown committed
3175 3176
  @param format_type		What kind of format should be supported
  @param var_ptr		Pointer to variable that should be updated
unknown's avatar
Merge  
unknown committed
3177

unknown's avatar
unknown committed
3178
  @retval
3179
    0 ok
unknown's avatar
unknown committed
3180
  @retval
3181 3182 3183
    1 error
*/

unknown's avatar
unknown committed
3184
static bool init_global_datetime_format(timestamp_type format_type,
3185
                                        DATE_TIME_FORMAT *format)
3186
{
3187 3188 3189 3190 3191
  /*
    Get command line option
    format->format.str is already set by my_getopt
  */
  format->format.length= strlen(format->format.str);
3192

3193
  if (parse_date_time_format(format_type, format))
3194
  {
3195 3196 3197
    fprintf(stderr, "Wrong date/time format specifier: %s\n",
            format->format.str);
    return true;
3198
  }
3199
  return false;
3200 3201
}

unknown's avatar
unknown committed
3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
SHOW_VAR com_status_vars[]= {
  {"admin_commands",       (char*) offsetof(STATUS_VAR, com_other), SHOW_LONG_STATUS},
  {"assign_to_keycache",   (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ASSIGN_TO_KEYCACHE]), SHOW_LONG_STATUS},
  {"alter_db",             (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_DB]), SHOW_LONG_STATUS},
  {"alter_db_upgrade",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_DB_UPGRADE]), SHOW_LONG_STATUS},
  {"alter_event",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_EVENT]), SHOW_LONG_STATUS},
  {"alter_function",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_FUNCTION]), SHOW_LONG_STATUS},
  {"alter_procedure",      (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_PROCEDURE]), SHOW_LONG_STATUS},
  {"alter_server",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_SERVER]), SHOW_LONG_STATUS},
  {"alter_table",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_TABLE]), SHOW_LONG_STATUS},
  {"alter_tablespace",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ALTER_TABLESPACE]), SHOW_LONG_STATUS},
  {"analyze",              (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ANALYZE]), SHOW_LONG_STATUS},
  {"begin",                (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_BEGIN]), SHOW_LONG_STATUS},
  {"binlog",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_BINLOG_BASE64_EVENT]), SHOW_LONG_STATUS},
  {"call_procedure",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CALL]), SHOW_LONG_STATUS},
  {"change_db",            (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CHANGE_DB]), SHOW_LONG_STATUS},
  {"change_master",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CHANGE_MASTER]), SHOW_LONG_STATUS},
  {"check",                (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CHECK]), SHOW_LONG_STATUS},
  {"checksum",             (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CHECKSUM]), SHOW_LONG_STATUS},
  {"commit",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_COMMIT]), SHOW_LONG_STATUS},
  {"create_db",            (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_DB]), SHOW_LONG_STATUS},
  {"create_event",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_EVENT]), SHOW_LONG_STATUS},
  {"create_function",      (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_SPFUNCTION]), SHOW_LONG_STATUS},
  {"create_index",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_INDEX]), SHOW_LONG_STATUS},
  {"create_procedure",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_PROCEDURE]), SHOW_LONG_STATUS},
  {"create_server",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_SERVER]), SHOW_LONG_STATUS},
  {"create_table",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_TABLE]), SHOW_LONG_STATUS},
  {"create_trigger",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_TRIGGER]), SHOW_LONG_STATUS},
  {"create_udf",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_FUNCTION]), SHOW_LONG_STATUS},
  {"create_user",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_USER]), SHOW_LONG_STATUS},
  {"create_view",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_CREATE_VIEW]), SHOW_LONG_STATUS},
  {"dealloc_sql",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DEALLOCATE_PREPARE]), SHOW_LONG_STATUS},
  {"delete",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DELETE]), SHOW_LONG_STATUS},
  {"delete_multi",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DELETE_MULTI]), SHOW_LONG_STATUS},
  {"do",                   (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DO]), SHOW_LONG_STATUS},
  {"drop_db",              (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_DB]), SHOW_LONG_STATUS},
  {"drop_event",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_EVENT]), SHOW_LONG_STATUS},
  {"drop_function",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_FUNCTION]), SHOW_LONG_STATUS},
  {"drop_index",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_INDEX]), SHOW_LONG_STATUS},
  {"drop_procedure",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_PROCEDURE]), SHOW_LONG_STATUS},
  {"drop_server",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_SERVER]), SHOW_LONG_STATUS},
  {"drop_table",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_TABLE]), SHOW_LONG_STATUS},
  {"drop_trigger",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_TRIGGER]), SHOW_LONG_STATUS},
  {"drop_user",            (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_USER]), SHOW_LONG_STATUS},
  {"drop_view",            (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_DROP_VIEW]), SHOW_LONG_STATUS},
  {"empty_query",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_EMPTY_QUERY]), SHOW_LONG_STATUS},
  {"execute_sql",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_EXECUTE]), SHOW_LONG_STATUS},
  {"flush",                (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_FLUSH]), SHOW_LONG_STATUS},
  {"grant",                (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_GRANT]), SHOW_LONG_STATUS},
  {"ha_close",             (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_HA_CLOSE]), SHOW_LONG_STATUS},
  {"ha_open",              (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_HA_OPEN]), SHOW_LONG_STATUS},
  {"ha_read",              (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_HA_READ]), SHOW_LONG_STATUS},
  {"help",                 (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_HELP]), SHOW_LONG_STATUS},
  {"insert",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_INSERT]), SHOW_LONG_STATUS},
  {"insert_select",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_INSERT_SELECT]), SHOW_LONG_STATUS},
  {"install_plugin",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_INSTALL_PLUGIN]), SHOW_LONG_STATUS},
  {"kill",                 (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_KILL]), SHOW_LONG_STATUS},
  {"load",                 (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_LOAD]), SHOW_LONG_STATUS},
  {"lock_tables",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_LOCK_TABLES]), SHOW_LONG_STATUS},
  {"optimize",             (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_OPTIMIZE]), SHOW_LONG_STATUS},
  {"preload_keys",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_PRELOAD_KEYS]), SHOW_LONG_STATUS},
  {"prepare_sql",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_PREPARE]), SHOW_LONG_STATUS},
  {"purge",                (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_PURGE]), SHOW_LONG_STATUS},
  {"purge_before_date",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_PURGE_BEFORE]), SHOW_LONG_STATUS},
  {"release_savepoint",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RELEASE_SAVEPOINT]), SHOW_LONG_STATUS},
  {"rename_table",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RENAME_TABLE]), SHOW_LONG_STATUS},
  {"rename_user",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RENAME_USER]), SHOW_LONG_STATUS},
  {"repair",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REPAIR]), SHOW_LONG_STATUS},
  {"replace",              (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REPLACE]), SHOW_LONG_STATUS},
  {"replace_select",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REPLACE_SELECT]), SHOW_LONG_STATUS},
  {"reset",                (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RESET]), SHOW_LONG_STATUS},
Marc Alff's avatar
Marc Alff committed
3273
  {"resignal",             (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_RESIGNAL]), SHOW_LONG_STATUS},
unknown's avatar
unknown committed
3274 3275 3276 3277 3278 3279 3280
  {"revoke",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REVOKE]), SHOW_LONG_STATUS},
  {"revoke_all",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_REVOKE_ALL]), SHOW_LONG_STATUS},
  {"rollback",             (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ROLLBACK]), SHOW_LONG_STATUS},
  {"rollback_to_savepoint",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_ROLLBACK_TO_SAVEPOINT]), SHOW_LONG_STATUS},
  {"savepoint",            (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SAVEPOINT]), SHOW_LONG_STATUS},
  {"select",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SELECT]), SHOW_LONG_STATUS},
  {"set_option",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SET_OPTION]), SHOW_LONG_STATUS},
Marc Alff's avatar
Marc Alff committed
3281
  {"signal",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SIGNAL]), SHOW_LONG_STATUS},
unknown's avatar
unknown committed
3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316
  {"show_authors",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_AUTHORS]), SHOW_LONG_STATUS},
  {"show_binlog_events",   (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_BINLOG_EVENTS]), SHOW_LONG_STATUS},
  {"show_binlogs",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_BINLOGS]), SHOW_LONG_STATUS},
  {"show_charsets",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CHARSETS]), SHOW_LONG_STATUS},
  {"show_collations",      (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_COLLATIONS]), SHOW_LONG_STATUS},
  {"show_contributors",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CONTRIBUTORS]), SHOW_LONG_STATUS},
  {"show_create_db",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_DB]), SHOW_LONG_STATUS},
  {"show_create_event",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_EVENT]), SHOW_LONG_STATUS},
  {"show_create_func",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_FUNC]), SHOW_LONG_STATUS},
  {"show_create_proc",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_PROC]), SHOW_LONG_STATUS},
  {"show_create_table",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE]), SHOW_LONG_STATUS},
  {"show_create_trigger",  (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_CREATE_TRIGGER]), SHOW_LONG_STATUS},
  {"show_databases",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_DATABASES]), SHOW_LONG_STATUS},
  {"show_engine_logs",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_ENGINE_LOGS]), SHOW_LONG_STATUS},
  {"show_engine_mutex",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_ENGINE_MUTEX]), SHOW_LONG_STATUS},
  {"show_engine_status",   (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_ENGINE_STATUS]), SHOW_LONG_STATUS},
  {"show_events",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_EVENTS]), SHOW_LONG_STATUS},
  {"show_errors",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_ERRORS]), SHOW_LONG_STATUS},
  {"show_fields",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_FIELDS]), SHOW_LONG_STATUS},
#ifndef DBUG_OFF
  {"show_function_code",   (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_FUNC_CODE]), SHOW_LONG_STATUS},
#endif
  {"show_function_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STATUS_FUNC]), SHOW_LONG_STATUS},
  {"show_grants",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_GRANTS]), SHOW_LONG_STATUS},
  {"show_keys",            (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_KEYS]), SHOW_LONG_STATUS},
  {"show_master_status",   (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_MASTER_STAT]), SHOW_LONG_STATUS},
  {"show_new_master",      (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_NEW_MASTER]), SHOW_LONG_STATUS},
  {"show_open_tables",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_OPEN_TABLES]), SHOW_LONG_STATUS},
  {"show_plugins",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PLUGINS]), SHOW_LONG_STATUS},
  {"show_privileges",      (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PRIVILEGES]), SHOW_LONG_STATUS},
#ifndef DBUG_OFF
  {"show_procedure_code",  (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PROC_CODE]), SHOW_LONG_STATUS},
#endif
  {"show_procedure_status",(char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STATUS_PROC]), SHOW_LONG_STATUS},
  {"show_processlist",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PROCESSLIST]), SHOW_LONG_STATUS},
unknown's avatar
unknown committed
3317 3318
  {"show_profile",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PROFILE]), SHOW_LONG_STATUS},
  {"show_profiles",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PROFILES]), SHOW_LONG_STATUS},
3319
  {"show_relaylog_events", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_RELAYLOG_EVENTS]), SHOW_LONG_STATUS},
unknown's avatar
unknown committed
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334
  {"show_slave_hosts",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_SLAVE_HOSTS]), SHOW_LONG_STATUS},
  {"show_slave_status",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_SLAVE_STAT]), SHOW_LONG_STATUS},
  {"show_status",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STATUS]), SHOW_LONG_STATUS},
  {"show_storage_engines", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_STORAGE_ENGINES]), SHOW_LONG_STATUS},
  {"show_table_status",    (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TABLE_STATUS]), SHOW_LONG_STATUS},
  {"show_tables",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TABLES]), SHOW_LONG_STATUS},
  {"show_triggers",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_TRIGGERS]), SHOW_LONG_STATUS},
  {"show_variables",       (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_VARIABLES]), SHOW_LONG_STATUS},
  {"show_warnings",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_WARNS]), SHOW_LONG_STATUS},
  {"slave_start",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SLAVE_START]), SHOW_LONG_STATUS},
  {"slave_stop",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SLAVE_STOP]), SHOW_LONG_STATUS},
  {"stmt_close",           (char*) offsetof(STATUS_VAR, com_stmt_close), SHOW_LONG_STATUS},
  {"stmt_execute",         (char*) offsetof(STATUS_VAR, com_stmt_execute), SHOW_LONG_STATUS},
  {"stmt_fetch",           (char*) offsetof(STATUS_VAR, com_stmt_fetch), SHOW_LONG_STATUS},
  {"stmt_prepare",         (char*) offsetof(STATUS_VAR, com_stmt_prepare), SHOW_LONG_STATUS},
unknown's avatar
unknown committed
3335
  {"stmt_reprepare",       (char*) offsetof(STATUS_VAR, com_stmt_reprepare), SHOW_LONG_STATUS},
unknown's avatar
unknown committed
3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
  {"stmt_reset",           (char*) offsetof(STATUS_VAR, com_stmt_reset), SHOW_LONG_STATUS},
  {"stmt_send_long_data",  (char*) offsetof(STATUS_VAR, com_stmt_send_long_data), SHOW_LONG_STATUS},
  {"truncate",             (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_TRUNCATE]), SHOW_LONG_STATUS},
  {"uninstall_plugin",     (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_UNINSTALL_PLUGIN]), SHOW_LONG_STATUS},
  {"unlock_tables",        (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_UNLOCK_TABLES]), SHOW_LONG_STATUS},
  {"update",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_UPDATE]), SHOW_LONG_STATUS},
  {"update_multi",         (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_UPDATE_MULTI]), SHOW_LONG_STATUS},
  {"xa_commit",            (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_COMMIT]),SHOW_LONG_STATUS},
  {"xa_end",               (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_END]),SHOW_LONG_STATUS},
  {"xa_prepare",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_PREPARE]),SHOW_LONG_STATUS},
  {"xa_recover",           (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_RECOVER]),SHOW_LONG_STATUS},
  {"xa_rollback",          (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_ROLLBACK]),SHOW_LONG_STATUS},
  {"xa_start",             (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_XA_START]),SHOW_LONG_STATUS},
3349
  {NullS, NullS, SHOW_LONG}
unknown's avatar
unknown committed
3350
};
3351

3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
/**
  Create the name of the default general log file
  
  @param[IN] buff    Location for building new string.
  @param[IN] log_ext The extension for the file (e.g .log)
  @returns Pointer to a new string containing the name
*/
static inline char *make_default_log_name(char *buff,const char* log_ext)
{
  return make_log_name(buff, default_logfile_name, log_ext);
}

Marc Alff's avatar
Marc Alff committed
3364
static int init_common_variables()
unknown's avatar
unknown committed
3365
{
3366
  char buff[FN_REFLEN];
unknown's avatar
unknown committed
3367
  umask(((~my_umask) & 0666));
unknown's avatar
Merge  
unknown committed
3368
  my_decimal_set_zero(&decimal_zero); // set decimal_zero constant;
unknown's avatar
unknown committed
3369 3370
  tzset();			// Set tzname

unknown's avatar
SCRUM  
unknown committed
3371
  max_system_variables.pseudo_thread_id= (ulong)~0;
3372
  server_start_time= flush_status_time= my_time(0);
3373 3374 3375 3376 3377 3378 3379
  /* TODO: remove this when my_time_t is 64 bit compatible */
  if (server_start_time >= (time_t) MY_TIME_T_MAX)
  {
    sql_print_error("This MySQL server doesn't support dates later then 2038");
    return 1;
  }

3380 3381
  rpl_filter= new Rpl_filter;
  binlog_filter= new Rpl_filter;
unknown's avatar
unknown committed
3382
  if (!rpl_filter || !binlog_filter)
3383 3384
  {
    sql_perror("Could not allocate replication and binlog filters");
3385
    return 1;
3386 3387
  }

3388 3389
  if (init_thread_environment() ||
      mysql_init_variables())
unknown's avatar
unknown committed
3390
    return 1;
unknown's avatar
unknown committed
3391

unknown's avatar
unknown committed
3392 3393 3394
#ifdef HAVE_TZNAME
  {
    struct tm tm_tmp;
3395
    localtime_r(&server_start_time,&tm_tmp);
3396 3397 3398 3399
    strmake(system_time_zone, tzname[tm_tmp.tm_isdst != 0 ? 1 : 0],
            sizeof(system_time_zone)-1);

 }
unknown's avatar
unknown committed
3400
#endif
3401
  /*
unknown's avatar
unknown committed
3402
    We set SYSTEM time zone as reasonable default and
3403 3404 3405 3406 3407
    also for failure of my_tz_init() and bootstrap mode.
    If user explicitly set time zone with --default-time-zone
    option we will change this value in my_tz_init().
  */
  global_system_variables.time_zone= my_tz_SYSTEM;
unknown's avatar
unknown committed
3408

unknown's avatar
unknown committed
3409
  /*
3410
    Init mutexes for the global MYSQL_BIN_LOG objects.
unknown's avatar
unknown committed
3411
    As safe_mutex depends on what MY_INIT() does, we can't init the mutexes of
3412 3413
    global MYSQL_BIN_LOGs in their constructors, because then they would be
    inited before MY_INIT(). So we do it here.
unknown's avatar
unknown committed
3414 3415
  */
  mysql_bin_log.init_pthread_objects();
3416

3417 3418 3419 3420 3421
  if (gethostname(glob_hostname,sizeof(glob_hostname)) < 0)
  {
    strmake(glob_hostname, STRING_WITH_LEN("localhost"));
    sql_print_warning("gethostname failed, using '%s' as hostname",
                      glob_hostname);
3422
    strmake(default_logfile_name, STRING_WITH_LEN("mysql"));
3423 3424
  }
  else
3425 3426 3427 3428
    strmake(default_logfile_name, glob_hostname, 
	    sizeof(default_logfile_name)-5);

  strmake(pidfile_name, default_logfile_name, sizeof(pidfile_name)-5);
3429
  strmov(fn_ext(pidfile_name),".pid");		// Add proper extension
unknown's avatar
unknown committed
3430

3431 3432 3433 3434 3435 3436 3437
  /*
    The default-storage-engine entry in my_long_options should have a
    non-null default value. It was earlier intialized as
    (longlong)"MyISAM" in my_long_options but this triggered a
    compiler error in the Sun Studio 12 compiler. As a work-around we
    set the def_value member to 0 in my_long_options and initialize it
    to the correct value here.
3438 3439 3440 3441

    From MySQL 5.5 onwards, the default storage engine is InnoDB
    (except in the embedded server, where the default continues to
    be MyISAM)
3442
  */
3443
#ifdef EMBEDDED_LIBRARY
3444
  default_storage_engine= const_cast<char *>("MyISAM");
3445 3446 3447
#else
  default_storage_engine= const_cast<char *>("InnoDB");
#endif
3448

3449 3450 3451
  /*
    Add server status variables to the dynamic list of
    status variables that is shown by SHOW STATUS.
3452
    Later, in plugin_init, and mysql_install_plugin
3453 3454 3455 3456 3457
    new entries could be added to that list.
  */
  if (add_status_vars(status_vars))
    return 1; // an error was already reported

unknown's avatar
unknown committed
3458 3459 3460 3461 3462
#ifndef DBUG_OFF
  /*
    We have few debug-only commands in com_status_vars, only visible in debug
    builds. for simplicity we enable the assert only in debug builds

unknown's avatar
unknown committed
3463
    There are 8 Com_ variables which don't have corresponding SQLCOM_ values:
unknown's avatar
unknown committed
3464 3465 3466 3467 3468 3469 3470 3471
    (TODO strictly speaking they shouldn't be here, should not have Com_ prefix
    that is. Perhaps Stmt_ ? Comstmt_ ? Prepstmt_ ?)

      Com_admin_commands       => com_other
      Com_stmt_close           => com_stmt_close
      Com_stmt_execute         => com_stmt_execute
      Com_stmt_fetch           => com_stmt_fetch
      Com_stmt_prepare         => com_stmt_prepare
unknown's avatar
unknown committed
3472
      Com_stmt_reprepare       => com_stmt_reprepare
unknown's avatar
unknown committed
3473 3474 3475
      Com_stmt_reset           => com_stmt_reset
      Com_stmt_send_long_data  => com_stmt_send_long_data

3476 3477 3478
    With this correction the number of Com_ variables (number of elements in
    the array, excluding the last element - terminator) must match the number
    of SQLCOM_ constants.
unknown's avatar
unknown committed
3479
  */
3480
  compile_time_assert(sizeof(com_status_vars)/sizeof(com_status_vars[0]) - 1 ==
unknown's avatar
unknown committed
3481
                     SQLCOM_END + 8);
unknown's avatar
unknown committed
3482 3483
#endif

Marc Alff's avatar
Marc Alff committed
3484
  if (get_options(&remaining_argc, &remaining_argv))
3485
    return 1;
3486 3487
  set_server_version();

unknown's avatar
unknown committed
3488 3489 3490
  DBUG_PRINT("info",("%s  Ver %s for %s on %s\n",my_progname,
		     server_version, SYSTEM_TYPE,MACHINE_TYPE));

unknown's avatar
Merge  
unknown committed
3491 3492 3493 3494
#ifdef HAVE_LARGE_PAGES
  /* Initialize large page size */
  if (opt_large_pages && (opt_large_page_size= my_get_large_page_size()))
  {
3495 3496
      DBUG_PRINT("info", ("Large page set, large_page_size = %d",
                 opt_large_page_size));
unknown's avatar
Merge  
unknown committed
3497 3498 3499
      my_use_large_pages= 1;
      my_large_page_size= opt_large_page_size;
  }
3500 3501 3502 3503 3504 3505 3506 3507
  else
  {
    opt_large_pages= 0;
    /* 
       Either not configured to use large pages or Linux haven't
       been compiled with large page support
    */
  }
unknown's avatar
Merge  
unknown committed
3508
#endif /* HAVE_LARGE_PAGES */
3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
#ifdef HAVE_SOLARIS_LARGE_PAGES
#define LARGE_PAGESIZE (4*1024*1024)  /* 4MB */
#define SUPER_LARGE_PAGESIZE (256*1024*1024)  /* 256MB */
  if (opt_large_pages)
  {
  /*
    tell the kernel that we want to use 4/256MB page for heap storage
    and also for the stack. We use 4 MByte as default and if the
    super-large-page is set we increase it to 256 MByte. 256 MByte
    is for server installations with GBytes of RAM memory where
    the MySQL Server will have page caches and other memory regions
    measured in a number of GBytes.
    We use as big pages as possible which isn't bigger than the above
    desired page sizes.
  */
   int nelem;
   int max_desired_page_size;
3526
   int max_page_size;
3527
   if (opt_super_large_pages)
3528
     max_page_size= SUPER_LARGE_PAGESIZE;
3529
   else
3530
     max_page_size= LARGE_PAGESIZE;
3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559
   nelem = getpagesizes(NULL, 0);
   if (nelem > 0)
   {
     size_t *pagesize = (size_t *) malloc(sizeof(size_t) * nelem);
     if (pagesize != NULL && getpagesizes(pagesize, nelem) > 0)
     {
       size_t i, max_page_size= 0;
       for (i= 0; i < nelem; i++)
       {
         if (pagesize[i] > max_page_size &&
             pagesize[i] <= max_desired_page_size)
            max_page_size= pagesize[i];
       }
       free(pagesize);
       if (max_page_size > 0)
       {
         struct memcntl_mha mpss;

         mpss.mha_cmd= MHA_MAPSIZE_BSSBRK;
         mpss.mha_pagesize= max_page_size;
         mpss.mha_flags= 0;
         memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mpss, 0, 0);
         mpss.mha_cmd= MHA_MAPSIZE_STACK;
         memcntl(NULL, 0, MC_HAT_ADVISE, (caddr_t)&mpss, 0, 0);
       }
     }
   }
  }
#endif /* HAVE_SOLARIS_LARGE_PAGES */
unknown's avatar
Merge  
unknown committed
3560

unknown's avatar
unknown committed
3561 3562
  /* connections and databases needs lots of files */
  {
3563
    uint files, wanted_files, max_open_files;
3564

3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579
    /* MyISAM requires two file handles per table. */
    wanted_files= 10+max_connections+table_cache_size*2;
    /*
      We are trying to allocate no less than max_connections*5 file
      handles (i.e. we are trying to set the limit so that they will
      be available).  In addition, we allocate no less than how much
      was already allocated.  However below we report a warning and
      recompute values only if we got less file handles than were
      explicitly requested.  No warning and re-computation occur if we
      can't get max_connections*5 but still got no less than was
      requested (value of wanted_files).
    */
    max_open_files= max(max(wanted_files, max_connections*5),
                        open_files_limit);
    files= my_set_max_open_files(max_open_files);
3580 3581

    if (files < wanted_files)
unknown's avatar
unknown committed
3582
    {
3583 3584
      if (!open_files_limit)
      {
3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
        /*
          If we have requested too much file handles than we bring
          max_connections in supported bounds.
        */
        max_connections= (ulong) min(files-10-TABLE_OPEN_CACHE_MIN*2,
                                     max_connections);
        /*
          Decrease table_cache_size according to max_connections, but
          not below TABLE_OPEN_CACHE_MIN.  Outer min() ensures that we
          never increase table_cache_size automatically (that could
          happen if max_connections is decreased above).
        */
        table_cache_size= (ulong) min(max((files-10-max_connections)/2,
                                          TABLE_OPEN_CACHE_MIN),
unknown's avatar
unknown committed
3599
                                      table_cache_size);
3600 3601 3602
	DBUG_PRINT("warning",
		   ("Changed limits: max_open_files: %u  max_connections: %ld  table_cache: %ld",
		    files, max_connections, table_cache_size));
unknown's avatar
unknown committed
3603
	if (global_system_variables.log_warnings)
3604
	  sql_print_warning("Changed limits: max_open_files: %u  max_connections: %ld  table_cache: %ld",
3605 3606
			files, max_connections, table_cache_size);
      }
unknown's avatar
unknown committed
3607
      else if (global_system_variables.log_warnings)
3608
	sql_print_warning("Could not increase number of max_open_files to more than %u (request: %u)", files, wanted_files);
unknown's avatar
unknown committed
3609
    }
unknown's avatar
unknown committed
3610
    open_files_limit= files;
unknown's avatar
unknown committed
3611 3612
  }
  unireg_init(opt_specialflag); /* Set up extern variabels */
3613 3614 3615 3616 3617 3618 3619
  if (!(my_default_lc_messages=
        my_locale_by_name(lc_messages)))
  {
    sql_print_error("Unknown locale: '%s'", lc_messages);
    return 1;
  }
  global_system_variables.lc_messages= my_default_lc_messages;
3620 3621
  if (init_errmessage())	/* Read error messages from file */
    return 1;
3622
  init_client_errs();
unknown's avatar
unknown committed
3623
  lex_init();
3624 3625
  if (item_create_init())
    return 1;
unknown's avatar
unknown committed
3626 3627
  item_init();
#ifdef USE_REGEX
unknown's avatar
unknown committed
3628
  my_regex_init(&my_charset_latin1);
unknown's avatar
unknown committed
3629
#endif
3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656
  /*
    Process a comma-separated character set list and choose
    the first available character set. This is mostly for
    test purposes, to be able to start "mysqld" even if
    the requested character set is not available (see bug#18743).
  */
  for (;;)
  {
    char *next_character_set_name= strchr(default_character_set_name, ',');
    if (next_character_set_name)
      *next_character_set_name++= '\0';
    if (!(default_charset_info=
          get_charset_by_csname(default_character_set_name,
                                MY_CS_PRIMARY, MYF(MY_WME))))
    {
      if (next_character_set_name)
      {
        default_character_set_name= next_character_set_name;
        default_collation_name= 0;          // Ignore collation
      }
      else
        return 1;                           // Eof of the list
    }
    else
      break;
  }

3657 3658
  if (default_collation_name)
  {
unknown's avatar
unknown committed
3659 3660
    CHARSET_INFO *default_collation;
    default_collation= get_charset_by_name(default_collation_name, MYF(0));
unknown's avatar
unknown committed
3661 3662
    if (!default_collation)
    {
3663
      sql_print_error(ER_DEFAULT(ER_UNKNOWN_COLLATION), default_collation_name);
unknown's avatar
unknown committed
3664 3665 3666
      return 1;
    }
    if (!my_charset_same(default_charset_info, default_collation))
3667
    {
3668
      sql_print_error(ER_DEFAULT(ER_COLLATION_CHARSET_MISMATCH),
3669 3670 3671 3672 3673 3674
		      default_collation_name,
		      default_charset_info->csname);
      return 1;
    }
    default_charset_info= default_collation;
  }
3675 3676 3677 3678
  /* Set collactions that depends on the default collation */
  global_system_variables.collation_server=	 default_charset_info;
  global_system_variables.collation_database=	 default_charset_info;
  global_system_variables.collation_connection=  default_charset_info;
3679
  global_system_variables.character_set_results= default_charset_info;
3680
  global_system_variables.character_set_client=  default_charset_info;
unknown's avatar
unknown committed
3681 3682 3683 3684 3685 3686
  if (!(character_set_filesystem= 
        get_charset_by_csname(character_set_filesystem_name,
                              MY_CS_PRIMARY, MYF(MY_WME))))
    return 1;
  global_system_variables.character_set_filesystem= character_set_filesystem;

3687 3688 3689
  if (!(my_default_lc_time_names=
        my_locale_by_name(lc_time_names_name)))
  {
unknown's avatar
unknown committed
3690
    sql_print_error("Unknown locale: '%s'", lc_time_names_name);
3691 3692 3693
    return 1;
  }
  global_system_variables.lc_time_names= my_default_lc_time_names;
3694

3695 3696 3697 3698 3699
  /* check log options and issue warnings if needed */
  if (opt_log && opt_logname && !(log_output_options & LOG_FILE) &&
      !(log_output_options & LOG_NONE))
    sql_print_warning("Although a path was specified for the "
                      "--log option, log tables are used. "
3700
                      "To enable logging to files use the --log-output option.");
3701 3702 3703 3704

  if (opt_slow_log && opt_slow_logname && !(log_output_options & LOG_FILE)
      && !(log_output_options & LOG_NONE))
    sql_print_warning("Although a path was specified for the "
Konstantin Osipov's avatar
Konstantin Osipov committed
3705
                      "--log-slow-queries option, log tables are used. "
3706
                      "To enable logging to files use the --log-output=file option.");
3707

3708 3709 3710 3711 3712 3713
#define FIX_LOG_VAR(VAR, ALT)                                   \
  if (!VAR || !*VAR)                                            \
  {                                                             \
    x_free(VAR); /* it could be an allocated empty string "" */ \
    VAR= my_strdup(ALT, MYF(0));                                \
  }
3714

3715 3716 3717 3718
  FIX_LOG_VAR(opt_logname,
              make_default_log_name(buff, ".log"));
  FIX_LOG_VAR(opt_slow_logname,
              make_default_log_name(buff, "-slow.log"));
3719

3720 3721 3722 3723 3724 3725
#if defined(ENABLED_DEBUG_SYNC)
  /* Initialize the debug sync facility. See debug_sync.cc. */
  if (debug_sync_init())
    return 1; /* purecov: tested */
#endif /* defined(ENABLED_DEBUG_SYNC) */

3726
#if (ENABLE_TEMP_POOL)
3727
  if (use_temp_pool && bitmap_init(&temp_pool,0,1024,1))
3728
    return 1;
3729 3730 3731 3732
#else
  use_temp_pool= 0;
#endif

unknown's avatar
unknown committed
3733
  if (my_database_names_init())
unknown's avatar
unknown committed
3734 3735
    return 1;

3736 3737 3738 3739 3740 3741
  /*
    Ensure that lower_case_table_names is set on system where we have case
    insensitive names.  If this is not done the users MyISAM tables will
    get corrupted if accesses with names of different case.
  */
  DBUG_PRINT("info", ("lower_case_table_names: %d", lower_case_table_names));
3742 3743
  lower_case_file_system= test_if_case_insensitive(mysql_real_data_home);
  if (!lower_case_table_names && lower_case_file_system == 1)
3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772
  {
    if (lower_case_table_names_used)
    {
      if (global_system_variables.log_warnings)
	sql_print_warning("\
You have forced lower_case_table_names to 0 through a command-line \
option, even though your file system '%s' is case insensitive.  This means \
that you can corrupt a MyISAM table by accessing it with different cases. \
You should consider changing lower_case_table_names to 1 or 2",
			mysql_real_data_home);
    }
    else
    {
      if (global_system_variables.log_warnings)
	sql_print_warning("Setting lower_case_table_names=2 because file system for %s is case insensitive", mysql_real_data_home);
      lower_case_table_names= 2;
    }
  }
  else if (lower_case_table_names == 2 &&
           !(lower_case_file_system=
             (test_if_case_insensitive(mysql_real_data_home) == 1)))
  {
    if (global_system_variables.log_warnings)
      sql_print_warning("lower_case_table_names was set to 2, even though your "
                        "the file system '%s' is case sensitive.  Now setting "
                        "lower_case_table_names to 0 to avoid future problems.",
			mysql_real_data_home);
    lower_case_table_names= 0;
  }
3773 3774 3775 3776 3777
  else
  {
    lower_case_file_system=
      (test_if_case_insensitive(mysql_real_data_home) == 1);
  }
3778 3779 3780 3781 3782 3783

  /* Reset table_alias_charset, now that lower_case_table_names is set. */
  table_alias_charset= (lower_case_table_names ?
			files_charset_info :
			&my_charset_bin);

unknown's avatar
unknown committed
3784 3785
  return 0;
}
unknown's avatar
unknown committed
3786

3787 3788

static int init_thread_environment()
unknown's avatar
unknown committed
3789
{
Marc Alff's avatar
Marc Alff committed
3790 3791 3792 3793
  mysql_mutex_init(key_LOCK_mysql_create_db,
                   &LOCK_mysql_create_db, MY_MUTEX_INIT_SLOW);
  mysql_mutex_init(key_LOCK_lock_db, &LOCK_lock_db, MY_MUTEX_INIT_SLOW);
  mysql_mutex_init(key_LOCK_open, &LOCK_open, MY_MUTEX_INIT_FAST);
Marc Alff's avatar
Marc Alff committed
3794
  mysql_mutex_init(key_LOCK_thread_count, &LOCK_thread_count, MY_MUTEX_INIT_FAST);
Marc Alff's avatar
Marc Alff committed
3795
  mysql_mutex_init(key_LOCK_mapped_file, &LOCK_mapped_file, MY_MUTEX_INIT_SLOW);
Marc Alff's avatar
Marc Alff committed
3796
  mysql_mutex_init(key_LOCK_status, &LOCK_status, MY_MUTEX_INIT_FAST);
Marc Alff's avatar
Marc Alff committed
3797
  mysql_mutex_init(key_LOCK_delayed_insert,
Marc Alff's avatar
Marc Alff committed
3798 3799 3800 3801 3802
                   &LOCK_delayed_insert, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_delayed_status,
                   &LOCK_delayed_status, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_delayed_create,
                   &LOCK_delayed_create, MY_MUTEX_INIT_SLOW);
Marc Alff's avatar
Marc Alff committed
3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821
  mysql_mutex_init(key_LOCK_manager,
                   &LOCK_manager, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_crypt, &LOCK_crypt, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_user_conn, &LOCK_user_conn, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_active_mi, &LOCK_active_mi, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_global_system_variables,
                   &LOCK_global_system_variables, MY_MUTEX_INIT_FAST);
  mysql_rwlock_init(key_rwlock_LOCK_system_variables_hash,
                    &LOCK_system_variables_hash);
  mysql_mutex_init(key_LOCK_global_read_lock,
                   &LOCK_global_read_lock, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_prepared_stmt_count,
                   &LOCK_prepared_stmt_count, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_error_messages,
                   &LOCK_error_messages, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_uuid_generator,
                   &LOCK_uuid_generator, MY_MUTEX_INIT_FAST);
  mysql_mutex_init(key_LOCK_connection_count,
                   &LOCK_connection_count, MY_MUTEX_INIT_FAST);
3822
#ifdef HAVE_OPENSSL
Marc Alff's avatar
Marc Alff committed
3823 3824
  mysql_mutex_init(key_LOCK_des_key_file,
                   &LOCK_des_key_file, MY_MUTEX_INIT_FAST);
unknown's avatar
unknown committed
3825 3826 3827 3828
#ifndef HAVE_YASSL
  openssl_stdlocks= (openssl_lock_t*) OPENSSL_malloc(CRYPTO_num_locks() *
                                                     sizeof(openssl_lock_t));
  for (int i= 0; i < CRYPTO_num_locks(); ++i)
3829
    mysql_rwlock_init(key_rwlock_openssl, &openssl_stdlocks[i].lock);
unknown's avatar
unknown committed
3830 3831 3832 3833 3834 3835
  CRYPTO_set_dynlock_create_callback(openssl_dynlock_create);
  CRYPTO_set_dynlock_destroy_callback(openssl_dynlock_destroy);
  CRYPTO_set_dynlock_lock_callback(openssl_lock);
  CRYPTO_set_locking_callback(openssl_lock_function);
  CRYPTO_set_id_callback(openssl_id_function);
#endif
3836
#endif
Marc Alff's avatar
Marc Alff committed
3837 3838 3839
  mysql_rwlock_init(key_rwlock_LOCK_sys_init_connect, &LOCK_sys_init_connect);
  mysql_rwlock_init(key_rwlock_LOCK_sys_init_slave, &LOCK_sys_init_slave);
  mysql_rwlock_init(key_rwlock_LOCK_grant, &LOCK_grant);
Marc Alff's avatar
Marc Alff committed
3840
  mysql_cond_init(key_COND_thread_count, &COND_thread_count, NULL);
Marc Alff's avatar
Marc Alff committed
3841
  mysql_cond_init(key_COND_refresh, &COND_refresh, NULL);
Marc Alff's avatar
Marc Alff committed
3842
  mysql_cond_init(key_COND_global_read_lock, &COND_global_read_lock, NULL);
Marc Alff's avatar
Marc Alff committed
3843 3844
  mysql_cond_init(key_COND_thread_cache, &COND_thread_cache, NULL);
  mysql_cond_init(key_COND_flush_thread_cache, &COND_flush_thread_cache, NULL);
Marc Alff's avatar
Marc Alff committed
3845
  mysql_cond_init(key_COND_manager, &COND_manager, NULL);
unknown's avatar
SCRUM  
unknown committed
3846
#ifdef HAVE_REPLICATION
Marc Alff's avatar
Marc Alff committed
3847 3848
  mysql_mutex_init(key_LOCK_rpl_status, &LOCK_rpl_status, MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_COND_rpl_status, &COND_rpl_status, NULL);
3849
#endif
Marc Alff's avatar
Marc Alff committed
3850 3851 3852
  mysql_mutex_init(key_LOCK_server_started,
                   &LOCK_server_started, MY_MUTEX_INIT_FAST);
  mysql_cond_init(key_COND_server_started, &COND_server_started, NULL);
unknown's avatar
Merge  
unknown committed
3853
  sp_cache_init();
3854
#ifdef HAVE_EVENT_SCHEDULER
3855
  Events::init_mutexes();
3856
#endif
unknown's avatar
unknown committed
3857 3858 3859 3860 3861
  /* Parameter for threads created for connections */
  (void) pthread_attr_init(&connection_attrib);
  (void) pthread_attr_setdetachstate(&connection_attrib,
				     PTHREAD_CREATE_DETACHED);
  pthread_attr_setscope(&connection_attrib, PTHREAD_SCOPE_SYSTEM);
unknown's avatar
unknown committed
3862

unknown's avatar
unknown committed
3863 3864 3865 3866 3867 3868 3869 3870 3871
  if (pthread_key_create(&THR_THD,NULL) ||
      pthread_key_create(&THR_MALLOC,NULL))
  {
    sql_print_error("Can't create thread-keys");
    return 1;
  }
  return 0;
}

3872

unknown's avatar
unknown committed
3873
#if defined(HAVE_OPENSSL) && !defined(HAVE_YASSL)
3874 3875 3876 3877 3878 3879 3880 3881 3882
static unsigned long openssl_id_function()
{ 
  return (unsigned long) pthread_self();
} 


static openssl_lock_t *openssl_dynlock_create(const char *file, int line)
{ 
  openssl_lock_t *lock= new openssl_lock_t;
3883
  mysql_rwlock_init(key_rwlock_openssl, &lock->lock);
3884 3885 3886 3887 3888 3889 3890
  return lock;
}


static void openssl_dynlock_destroy(openssl_lock_t *lock, const char *file, 
				    int line)
{
3891
  mysql_rwlock_destroy(&lock->lock);
3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916
  delete lock;
}


static void openssl_lock_function(int mode, int n, const char *file, int line)
{
  if (n < 0 || n > CRYPTO_num_locks())
  {
    /* Lock number out of bounds. */
    sql_print_error("Fatal: OpenSSL interface problem (n = %d)", n);
    abort();
  }
  openssl_lock(mode, &openssl_stdlocks[n], file, line);
}


static void openssl_lock(int mode, openssl_lock_t *lock, const char *file, 
			 int line)
{
  int err;
  char const *what;

  switch (mode) {
  case CRYPTO_LOCK|CRYPTO_READ:
    what = "read lock";
3917
    err= mysql_rwlock_rdlock(&lock->lock);
3918 3919 3920
    break;
  case CRYPTO_LOCK|CRYPTO_WRITE:
    what = "write lock";
3921
    err= mysql_rwlock_wrlock(&lock->lock);
3922 3923 3924 3925
    break;
  case CRYPTO_UNLOCK|CRYPTO_READ:
  case CRYPTO_UNLOCK|CRYPTO_WRITE:
    what = "unlock";
3926
    err= mysql_rwlock_unlock(&lock->lock);
3927 3928 3929 3930 3931 3932 3933 3934
    break;
  default:
    /* Unknown locking mode. */
    sql_print_error("Fatal: OpenSSL interface problem (mode=0x%x)", mode);
    abort();
  }
  if (err) 
  {
3935
    sql_print_error("Fatal: can't %s OpenSSL lock", what);
3936 3937 3938 3939 3940 3941
    abort();
  }
}
#endif /* HAVE_OPENSSL */


unknown's avatar
unknown committed
3942 3943
static void init_ssl()
{
unknown's avatar
unknown committed
3944
#ifdef HAVE_OPENSSL
Konstantin Osipov's avatar
Konstantin Osipov committed
3945
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
3946 3947
  if (opt_use_ssl)
  {
3948 3949
    enum enum_ssl_init_error error= SSL_INITERR_NOERROR;

3950 3951 3952
    /* having ssl_acceptor_fd != 0 signals the use of SSL */
    ssl_acceptor_fd= new_VioSSLAcceptorFd(opt_ssl_key, opt_ssl_cert,
					  opt_ssl_ca, opt_ssl_capath,
3953
					  opt_ssl_cipher, &error);
unknown's avatar
Merge  
unknown committed
3954
    DBUG_PRINT("info",("ssl_acceptor_fd: 0x%lx", (long) ssl_acceptor_fd));
unknown's avatar
unknown committed
3955
    if (!ssl_acceptor_fd)
3956
    {
3957
      sql_print_warning("Failed to setup SSL");
3958
      sql_print_warning("SSL error: %s", sslGetErrString(error));
unknown's avatar
unknown committed
3959
      opt_use_ssl = 0;
3960
      have_ssl= SHOW_OPTION_DISABLED;
3961 3962 3963 3964
    }
  }
  else
  {
3965
    have_ssl= SHOW_OPTION_DISABLED;
unknown's avatar
unknown committed
3966
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
3967 3968 3969
#else
  have_ssl= SHOW_OPTION_DISABLED;
#endif /* ! EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
3970 3971
  if (des_key_file)
    load_des_key_file(des_key_file);
unknown's avatar
unknown committed
3972
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
3973
}
unknown's avatar
unknown committed
3974

3975

3976 3977 3978
static void end_ssl()
{
#ifdef HAVE_OPENSSL
Konstantin Osipov's avatar
Konstantin Osipov committed
3979
#ifndef EMBEDDED_LIBRARY
3980 3981 3982 3983 3984
  if (ssl_acceptor_fd)
  {
    free_vio_ssl_acceptor_fd(ssl_acceptor_fd);
    ssl_acceptor_fd= 0;
  }
Konstantin Osipov's avatar
Konstantin Osipov committed
3985
#endif /* ! EMBEDDED_LIBRARY */
3986 3987 3988 3989
#endif /* HAVE_OPENSSL */
}


unknown's avatar
unknown committed
3990 3991
static int init_server_components()
{
3992
  FILE *reopen;
3993
  DBUG_ENTER("init_server_components");
unknown's avatar
unknown committed
3994 3995 3996 3997
  /*
    We need to call each of these following functions to ensure that
    all things are initialized so that unireg_abort() doesn't fail
  */
3998 3999
  mdl_init();
  if (table_def_init() | hostname_cache_init())
4000
    unireg_abort(1);
unknown's avatar
unknown committed
4001

4002
  query_cache_set_min_res_unit(query_cache_min_res_unit);
unknown's avatar
unknown committed
4003
  query_cache_init();
unknown's avatar
unknown committed
4004
  query_cache_resize(query_cache_size);
4005
  randominit(&sql_rand,(ulong) server_start_time,(ulong) server_start_time/2);
4006
  setup_fpu();
unknown's avatar
unknown committed
4007
  init_thr_lock();
unknown's avatar
SCRUM  
unknown committed
4008
#ifdef HAVE_REPLICATION
4009
  init_slave_list();
4010
#endif
unknown's avatar
unknown committed
4011

4012 4013
  /* Setup logs */

4014 4015 4016 4017 4018 4019
  /*
    Enable old-fashioned error log, except when the user has requested
    help information. Since the implementation of plugin server
    variables the help output is now written much later.
  */
  if (opt_error_log && !opt_help)
4020 4021
  {
    if (!log_error_file_ptr[0])
4022
      fn_format(log_error_file, pidfile_name, mysql_data_home, ".err",
4023 4024 4025 4026
                MY_REPLACE_EXT); /* replace '.<domain>' by '.err', bug#4997 */
    else
      fn_format(log_error_file, log_error_file_ptr, mysql_data_home, ".err",
                MY_UNPACK_FILENAME | MY_SAFE_PATH);
4027 4028 4029 4030 4031
    /*
      _ptr may have been set to my_disabled_option or "" if no argument was
      passed, but we need to show the real name in SHOW VARIABLES:
    */
    log_error_file_ptr= log_error_file;
4032
    if (!log_error_file[0])
4033
      opt_error_log= 0;                         // Too long file name
4034 4035 4036 4037 4038
    else
    {
#ifndef EMBEDDED_LIBRARY
      if (freopen(log_error_file, "a+", stdout))
#endif
4039
      {
4040
        reopen= freopen(log_error_file, "a+", stderr);
4041 4042
        setbuf(stderr, NULL);
      }
4043 4044 4045
    }
  }

4046 4047
  proc_info_hook= set_thd_proc_info;

Marc Alff's avatar
Marc Alff committed
4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
  /*
    Parsing the performance schema command line option may have reported
    warnings/information messages.
    Now that the logger is finally available, and redirected
    to the proper file when the --log--error option is used,
    print the buffered messages to the log.
  */
  buffered_logs.print();
  buffered_logs.cleanup();
#endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */

unknown's avatar
unknown committed
4060 4061 4062 4063 4064 4065
  if (xid_cache_init())
  {
    sql_print_error("Out of memory");
    unireg_abort(1);
  }

He Zhenxing's avatar
He Zhenxing committed
4066 4067 4068 4069 4070 4071 4072
  /* initialize delegates for extension observers */
  if (delegates_init())
  {
    sql_print_error("Initialize extension delegates failed");
    unireg_abort(1);
  }

unknown's avatar
unknown committed
4073
  /* need to configure logging before initializing storage engines */
unknown's avatar
Merge  
unknown committed
4074
  if (opt_log_slave_updates && !opt_bin_log)
unknown's avatar
unknown committed
4075
  {
4076
    sql_print_warning("You need to use --log-bin to make "
4077
                    "--log-slave-updates work.");
4078
  }
4079 4080 4081
  if (!opt_bin_log && binlog_format_used)
    sql_print_warning("You need to use --log-bin to make "
                      "--binlog-format work.");
4082

4083
  /* Check that we have not let the format to unspecified at this point */
4084
  DBUG_ASSERT((uint)global_system_variables.binlog_format <=
4085
              array_elements(binlog_format_names)-1);
4086

unknown's avatar
unknown committed
4087
#ifdef HAVE_REPLICATION
unknown's avatar
unknown committed
4088 4089
  if (opt_log_slave_updates && replicate_same_server_id)
  {
4090 4091 4092
    if (opt_bin_log)
    {
      sql_print_error("using --replicate-same-server-id in conjunction with \
unknown's avatar
unknown committed
4093 4094
--log-slave-updates is impossible, it would lead to infinite loops in this \
server.");
4095 4096 4097 4098 4099 4100
      unireg_abort(1);
    }
    else
      sql_print_warning("using --replicate-same-server-id in conjunction with \
--log-slave-updates would lead to infinite loops in this server. However this \
will be ignored as the --log-bin option is not defined.");
unknown's avatar
unknown committed
4101
  }
unknown's avatar
unknown committed
4102
#endif
4103

unknown's avatar
Merge  
unknown committed
4104
  if (opt_bin_log)
4105
  {
4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126
    /* Reports an error and aborts, if the --log-bin's path 
       is a directory.*/
    if (opt_bin_logname && 
        opt_bin_logname[strlen(opt_bin_logname) - 1] == FN_LIBCHAR)
    {
      sql_print_error("Path '%s' is a directory name, please specify \
a file name for --log-bin option", opt_bin_logname);
      unireg_abort(1);
    }

    /* Reports an error and aborts, if the --log-bin-index's path 
       is a directory.*/
    if (opt_binlog_index_name && 
        opt_binlog_index_name[strlen(opt_binlog_index_name) - 1] 
        == FN_LIBCHAR)
    {
      sql_print_error("Path '%s' is a directory name, please specify \
a file name for --log-bin-index option", opt_binlog_index_name);
      unireg_abort(1);
    }

unknown's avatar
Merge  
unknown committed
4127 4128 4129 4130
    char buf[FN_REFLEN];
    const char *ln;
    ln= mysql_bin_log.generate_name(opt_bin_logname, "-bin", 1, buf);
    if (!opt_bin_logname && !opt_binlog_index_name)
4131 4132
    {
      /*
unknown's avatar
Merge  
unknown committed
4133 4134 4135 4136 4137
        User didn't give us info to name the binlog index file.
        Picking `hostname`-bin.index like did in 4.x, causes replication to
        fail if the hostname is changed later. So, we would like to instead
        require a name. But as we don't want to break many existing setups, we
        only give warning, not error.
4138
      */
unknown's avatar
Merge  
unknown committed
4139 4140 4141 4142 4143
      sql_print_warning("No argument was provided to --log-bin, and "
                        "--log-bin-index was not used; so replication "
                        "may break when this MySQL server acts as a "
                        "master and has his hostname changed!! Please "
                        "use '--log-bin=%s' to avoid this problem.", ln);
4144
    }
unknown's avatar
Merge  
unknown committed
4145
    if (ln == buf)
4146
    {
unknown's avatar
Merge  
unknown committed
4147 4148
      my_free(opt_bin_logname, MYF(MY_ALLOW_ZERO_PTR));
      opt_bin_logname=my_strdup(buf, MYF(0));
4149
    }
4150
    if (mysql_bin_log.open_index_file(opt_binlog_index_name, ln, TRUE))
unknown's avatar
unknown committed
4151 4152 4153
    {
      unireg_abort(1);
    }
4154 4155
  }

4156 4157 4158 4159 4160 4161 4162
  /* call ha_init_key_cache() on all key caches to init them */
  process_key_caches(&ha_init_key_cache);

  /* Allow storage engine to give real error messages */
  if (ha_init_errors())
    DBUG_RETURN(1);

Marc Alff's avatar
Marc Alff committed
4163
  if (plugin_init(&remaining_argc, remaining_argv,
4164 4165 4166 4167 4168
                  (opt_noacl ? PLUGIN_INIT_SKIP_PLUGIN_TABLE : 0) |
                  (opt_help ? PLUGIN_INIT_SKIP_INITIALIZATION : 0)))
  {
    sql_print_error("Failed to initialize plugins.");
    unireg_abort(1);
unknown's avatar
unknown committed
4169
  }
4170
  plugins_are_initialized= TRUE;  /* Don't separate from init function */
unknown's avatar
unknown committed
4171

4172 4173 4174 4175 4176 4177
  have_csv= plugin_status(STRING_WITH_LEN("csv"),
                          MYSQL_STORAGE_ENGINE_PLUGIN);
  have_ndbcluster= plugin_status(STRING_WITH_LEN("ndbcluster"),
                                 MYSQL_STORAGE_ENGINE_PLUGIN);
  have_partitioning= plugin_status(STRING_WITH_LEN("partition"),
                                   MYSQL_STORAGE_ENGINE_PLUGIN);
unknown's avatar
unknown committed
4178 4179

  /* we do want to exit if there are any other unknown options */
Marc Alff's avatar
Marc Alff committed
4180
  if (remaining_argc > 1)
unknown's avatar
unknown committed
4181 4182
  {
    int ho_error;
unknown's avatar
unknown committed
4183
    struct my_option no_opts[]=
unknown's avatar
unknown committed
4184 4185 4186 4187 4188
    {
      {0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
    };
    /*
      We need to eat any 'loose' arguments first before we conclude
unknown's avatar
unknown committed
4189
      that there are unprocessed options.
unknown's avatar
unknown committed
4190 4191
    */
    my_getopt_skip_unknown= 0;
unknown's avatar
unknown committed
4192

Marc Alff's avatar
Marc Alff committed
4193
    if ((ho_error= handle_options(&remaining_argc, &remaining_argv, no_opts,
4194
                                  mysqld_get_one_option)))
unknown's avatar
unknown committed
4195
      unireg_abort(ho_error);
Marc Alff's avatar
Marc Alff committed
4196 4197 4198
    /* Add back the program name handle_options removes */
    remaining_argc++;
    remaining_argv--;
4199
    my_getopt_skip_unknown= TRUE;
unknown's avatar
unknown committed
4200

Marc Alff's avatar
Marc Alff committed
4201
    if (remaining_argc > 1)
unknown's avatar
unknown committed
4202 4203
    {
      fprintf(stderr, "%s: Too many arguments (first extra is '%s').\n"
unknown's avatar
unknown committed
4204
              "Use --verbose --help to get a list of available options\n",
Marc Alff's avatar
Marc Alff committed
4205
              my_progname, remaining_argv[1]);
unknown's avatar
unknown committed
4206 4207
      unireg_abort(1);
    }
unknown's avatar
unknown committed
4208 4209
  }

4210 4211 4212
  if (opt_help)
    unireg_abort(0);

unknown's avatar
unknown committed
4213
  /* if the errmsg.sys is not loaded, terminate to maintain behaviour */
4214 4215
  if (!DEFAULT_ERRMSGS[0][0])
    unireg_abort(1);  
unknown's avatar
unknown committed
4216

unknown's avatar
unknown committed
4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244
  /* We have to initialize the storage engines before CSV logging */
  if (ha_init())
  {
    sql_print_error("Can't init databases");
    unireg_abort(1);
  }

#ifdef WITH_CSV_STORAGE_ENGINE
  if (opt_bootstrap)
    log_output_options= LOG_FILE;
  else
    logger.init_log_tables();

  if (log_output_options & LOG_NONE)
  {
    /*
      Issue a warining if there were specified additional options to the
      log-output along with NONE. Probably this wasn't what user wanted.
    */
    if ((log_output_options & LOG_NONE) && (log_output_options & ~LOG_NONE))
      sql_print_warning("There were other values specified to "
                        "log-output besides NONE. Disabling slow "
                        "and general logs anyway.");
    logger.set_handlers(LOG_FILE, LOG_NONE, LOG_NONE);
  }
  else
  {
    /* fall back to the log files if tables are not present */
unknown's avatar
unknown committed
4245 4246
    LEX_STRING csv_name={C_STRING_WITH_LEN("csv")};
    if (!plugin_is_ready(&csv_name, MYSQL_STORAGE_ENGINE_PLUGIN))
unknown's avatar
unknown committed
4247
    {
4248
      /* purecov: begin inspected */
unknown's avatar
unknown committed
4249 4250
      sql_print_error("CSV engine is not present, falling back to the "
                      "log files");
unknown's avatar
unknown committed
4251
      log_output_options= (log_output_options & ~LOG_TABLE) | LOG_FILE;
4252
      /* purecov: end */
unknown's avatar
unknown committed
4253 4254 4255 4256 4257 4258 4259 4260 4261 4262
    }

    logger.set_handlers(LOG_FILE, opt_slow_log ? log_output_options:LOG_NONE,
                        opt_log ? log_output_options:LOG_NONE);
  }
#else
  logger.set_handlers(LOG_FILE, opt_slow_log ? LOG_FILE:LOG_NONE,
                      opt_log ? LOG_FILE:LOG_NONE);
#endif

4263
  /*
4264
    Set the default storage engine
4265
  */
4266 4267 4268 4269 4270 4271
  LEX_STRING name= { default_storage_engine, strlen(default_storage_engine) };
  plugin_ref plugin;
  handlerton *hton;
  if ((plugin= ha_resolve_by_name(0, &name)))
    hton= plugin_data(plugin, handlerton*);
  else
4272
  {
4273 4274 4275 4276 4277 4278 4279
    sql_print_error("Unknown/unsupported storage engine: %s",
                    default_storage_engine);
    unireg_abort(1);
  }
  if (!ha_storage_engine_is_enabled(hton))
  {
    if (!opt_bootstrap)
4280
    {
4281 4282
      sql_print_error("Default storage engine (%s) is not available",
                      default_storage_engine);
4283 4284
      unireg_abort(1);
    }
4285 4286 4287 4288 4289 4290 4291 4292 4293 4294
    DBUG_ASSERT(global_system_variables.table_plugin);
  }
  else
  {
    /*
      Need to unlock as global_system_variables.table_plugin
      was acquired during plugin_init()
    */
    plugin_unlock(0, global_system_variables.table_plugin);
    global_system_variables.table_plugin= plugin;
4295 4296
  }

unknown's avatar
unknown committed
4297 4298 4299 4300
  tc_log= (total_ha_2pc > 1 ? (opt_bin_log  ?
                               (TC_LOG *) &mysql_bin_log :
                               (TC_LOG *) &tc_log_mmap) :
           (TC_LOG *) &tc_log_dummy);
unknown's avatar
unknown committed
4301

unknown's avatar
unknown committed
4302
  if (tc_log->open(opt_bin_log ? opt_bin_logname : opt_tc_log_file))
unknown's avatar
Merge  
unknown committed
4303 4304 4305 4306 4307
  {
    sql_print_error("Can't init tc log");
    unireg_abort(1);
  }

unknown's avatar
unknown committed
4308 4309 4310 4311 4312
  if (ha_recover(0))
  {
    unireg_abort(1);
  }

unknown's avatar
Merge  
unknown committed
4313
  if (opt_bin_log && mysql_bin_log.open(opt_bin_logname, LOG_BIN, 0,
4314
                                        WRITE_CACHE, 0, max_binlog_size, 0, TRUE))
unknown's avatar
unknown committed
4315
    unireg_abort(1);
unknown's avatar
Merge  
unknown committed
4316 4317 4318

#ifdef HAVE_REPLICATION
  if (opt_bin_log && expire_logs_days)
4319
  {
4320
    time_t purge_time= server_start_time - expire_logs_days*24*60*60;
unknown's avatar
Merge  
unknown committed
4321 4322
    if (purge_time >= 0)
      mysql_bin_log.purge_logs_before_date(purge_time);
4323
  }
unknown's avatar
Merge  
unknown committed
4324
#endif
unknown's avatar
unknown committed
4325 4326 4327 4328
#ifdef __NETWARE__
  /* Increasing stacksize of threads on NetWare */
  pthread_attr_setstacksize(&connection_attrib, NW_THD_STACKSIZE);
#endif
unknown's avatar
Merge  
unknown committed
4329 4330 4331

  if (opt_myisam_log)
    (void) mi_log(1);
unknown's avatar
unknown committed
4332

unknown's avatar
unknown committed
4333
#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) && !defined(EMBEDDED_LIBRARY)
4334
  if (locked_in_memory && !getuid())
4335
  {
4336
    if (setreuid((uid_t)-1, 0) == -1)
4337
    {                        // this should never happen
4338
      sql_perror("setreuid");
4339 4340
      unireg_abort(1);
    }
4341 4342
    if (mlockall(MCL_CURRENT))
    {
4343
      if (global_system_variables.log_warnings)
4344
	sql_print_warning("Failed to lock memory. Errno: %d\n",errno);
unknown's avatar
unknown committed
4345
      locked_in_memory= 0;
4346
    }
4347 4348
    if (user_info)
      set_user(mysqld_user, user_info);
4349
  }
unknown's avatar
unknown committed
4350
  else
4351
#endif
unknown's avatar
unknown committed
4352
    locked_in_memory=0;
4353

4354
  ft_init_stopwords();
unknown's avatar
unknown committed
4355

unknown's avatar
unknown committed
4356
  init_max_user_conn();
4357
  init_update_queries();
4358
  DBUG_RETURN(0);
unknown's avatar
unknown committed
4359
}
unknown's avatar
unknown committed
4360

4361

4362
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
4363

unknown's avatar
unknown committed
4364 4365 4366
static void create_shutdown_thread()
{
#ifdef __WIN__
4367 4368
  hEventShutdown=CreateEvent(0, FALSE, FALSE, shutdown_event_name);
  pthread_t hThread;
Marc Alff's avatar
Marc Alff committed
4369 4370
  if (mysql_thread_create(key_thread_handle_shutdown,
                          &hThread, &connection_attrib, handle_shutdown, 0))
4371
    sql_print_warning("Can't create thread to handle shutdown requests");
unknown's avatar
unknown committed
4372

4373 4374
  // On "Stop Service" we have to do regular shutdown
  Service.SetShutdownEvent(hEventShutdown);
unknown's avatar
unknown committed
4375
#endif /* __WIN__ */
unknown's avatar
unknown committed
4376
}
unknown's avatar
unknown committed
4377

4378
#endif /* EMBEDDED_LIBRARY */
4379 4380


Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
4381
#if (defined(_WIN32) || defined(HAVE_SMEM)) && !defined(EMBEDDED_LIBRARY)
4382
static void handle_connections_methods()
unknown's avatar
unknown committed
4383
{
4384 4385
  pthread_t hThread;
  DBUG_ENTER("handle_connections_methods");
unknown's avatar
unknown committed
4386
  if (hPipe == INVALID_HANDLE_VALUE &&
4387 4388
      (!have_tcpip || opt_disable_networking) &&
      !opt_enable_shared_memory)
unknown's avatar
unknown committed
4389
  {
unknown's avatar
unknown committed
4390
    sql_print_error("TCP/IP, --shared-memory, or --named-pipe should be configured on NT OS");
4391
    unireg_abort(1);				// Will not return
unknown's avatar
unknown committed
4392
  }
4393

Marc Alff's avatar
Marc Alff committed
4394 4395
  mysql_mutex_lock(&LOCK_thread_count);
  mysql_cond_init(key_COND_handler_count, &COND_handler_count, NULL);
4396 4397
  handler_count=0;
  if (hPipe != INVALID_HANDLE_VALUE)
unknown's avatar
unknown committed
4398
  {
4399
    handler_count++;
Marc Alff's avatar
Marc Alff committed
4400 4401 4402
    if (mysql_thread_create(key_thread_handle_con_namedpipes,
                            &hThread, &connection_attrib,
                            handle_connections_namedpipes, 0))
unknown's avatar
unknown committed
4403
    {
4404
      sql_print_warning("Can't create thread to handle named pipes");
4405 4406 4407 4408 4409 4410
      handler_count--;
    }
  }
  if (have_tcpip && !opt_disable_networking)
  {
    handler_count++;
Marc Alff's avatar
Marc Alff committed
4411 4412 4413
    if (mysql_thread_create(key_thread_handle_con_sockets,
                            &hThread, &connection_attrib,
                            handle_connections_sockets_thread, 0))
4414
    {
4415
      sql_print_warning("Can't create thread to handle TCP/IP");
4416 4417 4418 4419 4420 4421 4422
      handler_count--;
    }
  }
#ifdef HAVE_SMEM
  if (opt_enable_shared_memory)
  {
    handler_count++;
Marc Alff's avatar
Marc Alff committed
4423 4424 4425
    if (mysql_thread_create(key_thread_handle_con_sharedmem,
                            &hThread, &connection_attrib,
                            handle_connections_shared_memory, 0))
4426
    {
4427
      sql_print_warning("Can't create thread to handle shared memory");
4428
      handler_count--;
unknown's avatar
unknown committed
4429 4430
    }
  }
4431
#endif 
unknown's avatar
unknown committed
4432

4433
  while (handler_count > 0)
Marc Alff's avatar
Marc Alff committed
4434 4435
    mysql_cond_wait(&COND_handler_count, &LOCK_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);
4436 4437
  DBUG_VOID_RETURN;
}
4438 4439 4440

void decrement_handler_count()
{
Marc Alff's avatar
Marc Alff committed
4441
  mysql_mutex_lock(&LOCK_thread_count);
4442
  handler_count--;
Marc Alff's avatar
Marc Alff committed
4443 4444
  mysql_cond_signal(&COND_handler_count);
  mysql_mutex_unlock(&LOCK_thread_count);
4445
  my_thread_end();
4446 4447 4448
}
#else
#define decrement_handler_count()
Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
4449
#endif /* defined(_WIN32) || defined(HAVE_SMEM) */
4450 4451


4452
#ifndef EMBEDDED_LIBRARY
4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489
#ifndef DBUG_OFF
/*
  Debugging helper function to keep the locale database
  (see sql_locale.cc) and max_month_name_length and
  max_day_name_length variable values in consistent state.
*/
static void test_lc_time_sz()
{
  DBUG_ENTER("test_lc_time_sz");
  for (MY_LOCALE **loc= my_locales; *loc; loc++)
  {
    uint max_month_len= 0;
    uint max_day_len = 0;
    for (const char **month= (*loc)->month_names->type_names; *month; month++)
    {
      set_if_bigger(max_month_len,
                    my_numchars_mb(&my_charset_utf8_general_ci,
                                   *month, *month + strlen(*month)));
    }
    for (const char **day= (*loc)->day_names->type_names; *day; day++)
    {
      set_if_bigger(max_day_len,
                    my_numchars_mb(&my_charset_utf8_general_ci,
                                   *day, *day + strlen(*day)));
    }
    if ((*loc)->max_month_name_length != max_month_len ||
        (*loc)->max_day_name_length != max_day_len)
    {
      DBUG_PRINT("Wrong max day name(or month name) length for locale:",
                 ("%s", (*loc)->name));
      DBUG_ASSERT(0);
    }
  }
  DBUG_VOID_RETURN;
}
#endif//DBUG_OFF

unknown's avatar
unknown committed
4490 4491 4492
#ifdef __WIN__
int win_main(int argc, char **argv)
#else
4493
int mysqld_main(int argc, char **argv)
unknown's avatar
unknown committed
4494 4495
#endif
{
Marc Alff's avatar
Marc Alff committed
4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617
  /*
    Perform basic thread library and malloc initialization,
    to be able to read defaults files and parse options.
  */
  my_progname= argv[0];
  if (my_basic_init())
  {
    fprintf(stderr, "my_basic_init() failed.");
    return 1;
  }

  orig_argc= argc;
  orig_argv= argv;
  if (load_defaults(MYSQL_CONFIG_NAME, load_default_groups, &argc, &argv))
    return 1;
  defaults_argc= argc;
  defaults_argv= argv;
  remaining_argc= argc;
  remaining_argv= argv;

  /* Must be initialized early for comparison of options name */
  system_charset_info= &my_charset_utf8_general_ci;

  sys_var_init();

#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
  /*
    The performance schema needs to be initialized as early as possible,
    before to-be-instrumented objects of the server are initialized.
  */
  int ho_error;
  DYNAMIC_ARRAY all_early_options;

  my_getopt_register_get_addr(NULL);
  /* Skip unknown options so that they may be processed later */
  my_getopt_skip_unknown= TRUE;

  /* prepare all_early_options array */
  my_init_dynamic_array(&all_early_options, sizeof(my_option), 100, 25);
  sys_var_add_options(&all_early_options, sys_var::PARSE_EARLY);
  add_terminator(&all_early_options);

  /*
    Logs generated while parsing the command line
    options are buffered and printed later.
  */
  buffered_logs.init();
  my_getopt_error_reporter= buffered_option_error_reporter;

  ho_error= handle_options(&remaining_argc, &remaining_argv,
                           (my_option*)(all_early_options.buffer), NULL);
  delete_dynamic(&all_early_options);
  if (ho_error == 0)
  {
    /* Add back the program name handle_options removes */
    remaining_argc++;
    remaining_argv--;
    if (pfs_param.m_enabled)
    {
      PSI_hook= initialize_performance_schema(&pfs_param);
      if (PSI_hook == NULL)
      {
        pfs_param.m_enabled= false;
        buffered_logs.buffer(WARNING_LEVEL,
                             "Performance schema disabled (reason: init failed).");
      }
      else
      {
        buffered_logs.buffer(INFORMATION_LEVEL,
                             "Performance schema enabled.");
      }
    }
    else
    {
      buffered_logs.buffer(INFORMATION_LEVEL,
                           "Performance schema disabled (reason: start parameters).");
    }
  }
#else
  /*
    Other provider of the instrumentation interface should
    initialize PSI_hook here:
    - HAVE_PSI_INTERFACE is for the instrumentation interface
    - WITH_PERFSCHEMA_STORAGE_ENGINE is for one implementation
      of the interface,
    but there could be alternate implementations, which is why
    these two defines are kept separate.
  */
#endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */

#ifdef HAVE_PSI_INTERFACE
  /*
    Obtain the current performance schema instrumentation interface,
    if available.
  */
  if (PSI_hook)
    PSI_server= (PSI*) PSI_hook->get_interface(PSI_CURRENT_VERSION);

  if (PSI_server)
  {
    /*
      Now that we have parsed the command line arguments, and have initialized
      the performance schema itself, the next step is to register all the
      server instruments.
    */
    init_server_psi_keys();
    /* Instrument the main thread */
    PSI_thread *psi= PSI_server->new_thread(key_thread_main, NULL, 0);
    if (psi)
      PSI_server->set_thread(psi);

    /*
      Now that some instrumentation is in place,
      recreate objects which were initialised early,
      so that they are instrumented as well.
    */
    my_thread_basic_global_reinit();
  }
#endif /* HAVE_PSI_INTERFACE */

  my_init();                                   // init my_sys library & pthreads
  init_error_log_mutex();
4618

4619 4620 4621 4622 4623 4624 4625
  /* Set signal used to kill MySQL */
#if defined(SIGUSR2)
  thr_kill_signal= thd_lib_detected == THD_LIB_LT ? SIGINT : SIGUSR2;
#else
  thr_kill_signal= SIGINT;
#endif

4626 4627 4628
  /* Initialize audit interface globals. Audit plugins are inited later. */
  mysql_audit_initialize();

4629 4630 4631 4632 4633 4634
  /*
    Perform basic logger initialization logger. Should be called after
    MY_INIT, as it initializes mutexes. Log tables are inited later.
  */
  logger.init_base();

Marc Alff's avatar
Marc Alff committed
4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
  if (ho_error)
  {
    /*
      Parsing command line option failed,
      Since we don't have a workable remaining_argc/remaining_argv
      to continue the server initialization, this is as far as this
      code can go.
      This is the best effort to log meaningful messages:
      - messages will be printed to stderr, which is not redirected yet,
      - messages will be printed in the NT event log, for windows.
    */
    buffered_logs.print();
    buffered_logs.cleanup();
    /*
      Not enough initializations for unireg_abort()
      Using exit() for windows.
    */
    exit (ho_error);
  }
#endif /* WITH_PERFSCHEMA_STORAGE_ENGINE */

unknown's avatar
unknown committed
4657
#ifdef _CUSTOMSTARTUPCONFIG_
unknown's avatar
unknown committed
4658 4659 4660
  if (_cust_check_startup())
  {
    / * _cust_check_startup will report startup failure error * /
unknown's avatar
Merge  
unknown committed
4661
    exit(1);
unknown's avatar
unknown committed
4662 4663
  }
#endif
unknown's avatar
unknown committed
4664

4665
#ifdef	__WIN__
unknown's avatar
unknown committed
4666 4667 4668 4669
  /*
    Before performing any socket operation (like retrieving hostname
    in init_common_variables we have to call WSAStartup
  */
4670 4671 4672 4673
  {
    WSADATA WsaData;
    if (SOCKET_ERROR == WSAStartup (0x0101, &WsaData))
    {
unknown's avatar
unknown committed
4674
      /* errors are not read yet, so we use english text here */
4675
      my_message(ER_WSAS_FAILED, "WSAStartup Failed", MYF(0));
Marc Alff's avatar
Marc Alff committed
4676 4677
      /* Not enough initializations for unireg_abort() */
      return 1;
4678 4679 4680 4681
    }
  }
#endif /* __WIN__ */

Marc Alff's avatar
Marc Alff committed
4682
  if (init_common_variables())
4683
    unireg_abort(1);				// Will do exit
unknown's avatar
unknown committed
4684 4685

  init_signals();
4686
#if defined(__ia64__) || defined(__ia64)
4687 4688 4689 4690
  /*
    Peculiar things with ia64 platforms - it seems we only have half the
    stack size in reality, so we have to double it here
  */
4691
  pthread_attr_setstacksize(&connection_attrib,my_thread_stack_size*2);
4692
#else
4693
  pthread_attr_setstacksize(&connection_attrib,my_thread_stack_size);
4694
#endif
4695 4696 4697 4698 4699
#ifdef HAVE_PTHREAD_ATTR_GETSTACKSIZE
  {
    /* Retrieve used stack size;  Needed for checking stack overflows */
    size_t stack_size= 0;
    pthread_attr_getstacksize(&connection_attrib, &stack_size);
4700 4701 4702
#if defined(__ia64__) || defined(__ia64)
    stack_size/= 2;
#endif
4703
    /* We must check if stack_size = 0 as Solaris 2.9 can return 0 here */
4704
    if (stack_size && stack_size < my_thread_stack_size)
4705 4706
    {
      if (global_system_variables.log_warnings)
unknown's avatar
unknown committed
4707
	sql_print_warning("Asked for %lu thread stack, but got %ld",
4708
			  my_thread_stack_size, (long) stack_size);
4709
#if defined(__ia64__) || defined(__ia64)
4710
      my_thread_stack_size= stack_size*2;
4711
#else
4712
      my_thread_stack_size= stack_size;
4713
#endif
4714 4715 4716
    }
  }
#endif
4717 4718 4719 4720
#ifdef __NETWARE__
  /* Increasing stacksize of threads on NetWare */
  pthread_attr_setstacksize(&connection_attrib, NW_THD_STACKSIZE);
#endif
unknown's avatar
unknown committed
4721

4722
  (void) thr_setconcurrency(concurrency);	// 10 by default
unknown's avatar
unknown committed
4723

4724 4725
  select_thread=pthread_self();
  select_thread_in_use=1;
unknown's avatar
unknown committed
4726 4727 4728 4729 4730 4731

#ifdef HAVE_LIBWRAP
  libwrapName= my_progname+dirname_length(my_progname);
  openlog(libwrapName, LOG_PID, LOG_AUTH);
#endif

4732 4733 4734 4735
#ifndef DBUG_OFF
  test_lc_time_sz();
#endif

unknown's avatar
unknown committed
4736 4737 4738
  /*
    We have enough space for fiddling with the argv, continue
  */
unknown's avatar
unknown committed
4739
  check_data_home(mysql_real_data_home);
unknown's avatar
unknown committed
4740
  if (my_setwd(mysql_real_data_home,MYF(MY_WME)) && !opt_help)
unknown's avatar
unknown committed
4741
    unireg_abort(1);				/* purecov: inspected */
unknown's avatar
unknown committed
4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752

  if ((user_info= check_user(mysqld_user)))
  {
#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT)
    if (locked_in_memory) // getuid() == 0 here
      set_effective_user(user_info);
    else
#endif
      set_user(mysqld_user, user_info);
  }

unknown's avatar
unknown committed
4753 4754
  if (opt_bin_log && !server_id)
  {
4755
    server_id= 1;
unknown's avatar
unknown committed
4756
#ifdef EXTRA_DEBUG
4757 4758 4759 4760
    sql_print_warning("You have enabled the binary log, but you haven't set "
                      "server-id to a non-zero value: we force server id to 1; "
                      "updates will be logged to the binary log, but "
                      "connections from slaves will not be accepted.");
4761
#endif
unknown's avatar
unknown committed
4762 4763 4764
  }

  if (init_server_components())
unknown's avatar
unknown committed
4765
    unireg_abort(1);
unknown's avatar
unknown committed
4766

4767
  init_ssl();
unknown's avatar
unknown committed
4768 4769
  network_init();

unknown's avatar
unknown committed
4770 4771 4772
#ifdef __WIN__
  if (!opt_console)
  {
4773 4774
    freopen(log_error_file,"a+",stdout);
    freopen(log_error_file,"a+",stderr);
4775
    setbuf(stderr, NULL);
unknown's avatar
unknown committed
4776
    FreeConsole();				// Remove window
4777
  }
unknown's avatar
unknown committed
4778 4779
#endif

4780 4781 4782 4783 4784 4785
  /*
   Initialize my_str_malloc() and my_str_free()
  */
  my_str_malloc= &my_str_malloc_mysqld;
  my_str_free= &my_str_free_mysqld;

unknown's avatar
unknown committed
4786 4787 4788 4789
  /*
    init signals & alarm
    After this we can't quit by a simple unireg_abort
  */
4790
  error_handler_hook= my_message_sql;
unknown's avatar
unknown committed
4791
  start_signal_handler();				// Creates pidfile
4792

4793
  if (mysql_rm_tmp_tables() || acl_init(opt_noacl) ||
4794
      my_tz_init((THD *)0, default_tz_name, opt_bootstrap))
unknown's avatar
unknown committed
4795 4796 4797
  {
    abort_loop=1;
    select_thread_in_use=0;
unknown's avatar
unknown committed
4798 4799 4800
#ifndef __NETWARE__
    (void) pthread_kill(signal_thread, MYSQL_KILL_SIGNAL);
#endif /* __NETWARE__ */
4801

unknown's avatar
unknown committed
4802
    if (!opt_bootstrap)
Marc Alff's avatar
Marc Alff committed
4803
      mysql_file_delete(key_file_pid, pidfile_name, MYF(MY_WME)); // Not needed anymore
4804

4805
    if (unix_sock != INVALID_SOCKET)
4806
      unlink(mysqld_unix_port);
unknown's avatar
unknown committed
4807 4808
    exit(1);
  }
4809

unknown's avatar
unknown committed
4810
  if (!opt_noacl)
4811
    (void) grant_init();
unknown's avatar
unknown committed
4812

unknown's avatar
unknown committed
4813 4814 4815
  if (!opt_bootstrap)
    servers_init(0);

unknown's avatar
unknown committed
4816
  if (!opt_noacl)
4817 4818
  {
#ifdef HAVE_DLOPEN
unknown's avatar
unknown committed
4819 4820
    udf_init();
#endif
4821
  }
4822

4823
  init_status_vars();
unknown's avatar
unknown committed
4824 4825
  if (opt_bootstrap) /* If running with bootstrap, do not start replication. */
    opt_skip_slave_start= 1;
4826 4827 4828 4829 4830 4831 4832 4833 4834 4835
  /*
    init_slave() must be called after the thread keys are created.
    Some parts of the code (e.g. SHOW STATUS LIKE 'slave_running' and other
    places) assume that active_mi != 0, so let's fail if it's 0 (out of
    memory); a message has already been printed.
  */
  if (init_slave() && !active_mi)
  {
    unireg_abort(1);
  }
4836

Marc Alff's avatar
Marc Alff committed
4837 4838 4839 4840 4841 4842 4843
#ifdef WITH_PERFSCHEMA_STORAGE_ENGINE
  initialize_performance_schema_acl(opt_bootstrap);
  check_performance_schema();
#endif

  initialize_information_schema_acl();

4844 4845 4846 4847 4848
  execute_ddl_log_recovery();

  if (Events::init(opt_noacl || opt_bootstrap))
    unireg_abort(1);

unknown's avatar
unknown committed
4849 4850
  if (opt_bootstrap)
  {
4851
    select_thread_in_use= 0;                    // Allow 'kill' to work
Marc Alff's avatar
Marc Alff committed
4852
    bootstrap(mysql_stdin);
unknown's avatar
Merge  
unknown committed
4853
    unireg_abort(bootstrap_error ? 1 : 0);
unknown's avatar
unknown committed
4854
  }
4855
  if (opt_init_file && *opt_init_file)
unknown's avatar
unknown committed
4856 4857 4858 4859
  {
    if (read_init_file(opt_init_file))
      unireg_abort(1);
  }
unknown's avatar
unknown committed
4860

unknown's avatar
unknown committed
4861
  create_shutdown_thread();
4862
  start_handle_manager();
unknown's avatar
unknown committed
4863

4864
  sql_print_information(ER_DEFAULT(ER_STARTUP),my_progname,server_version,
unknown's avatar
unknown committed
4865
                        ((unix_sock == INVALID_SOCKET) ? (char*) ""
unknown's avatar
Merge  
unknown committed
4866
                                                       : mysqld_unix_port),
unknown's avatar
unknown committed
4867
                         mysqld_port,
unknown's avatar
Merge  
unknown committed
4868
                         MYSQL_COMPILATION_COMMENT);
4869 4870 4871
#if defined(_WIN32) && !defined(EMBEDDED_LIBRARY)
  Service.SetRunning();
#endif
unknown's avatar
unknown committed
4872

unknown's avatar
unknown committed
4873 4874

  /* Signal threads waiting for server to be started */
Marc Alff's avatar
Marc Alff committed
4875
  mysql_mutex_lock(&LOCK_server_started);
unknown's avatar
unknown committed
4876
  mysqld_server_started= 1;
Marc Alff's avatar
Marc Alff committed
4877 4878
  mysql_cond_signal(&COND_server_started);
  mysql_mutex_unlock(&LOCK_server_started);
unknown's avatar
unknown committed
4879

4880
#if defined(_WIN32) || defined(HAVE_SMEM)
4881
  handle_connections_methods();
unknown's avatar
unknown committed
4882
#else
4883 4884
  handle_connections_sockets();
#endif /* _WIN32 || HAVE_SMEM */
unknown's avatar
unknown committed
4885 4886

  /* (void) pthread_attr_destroy(&connection_attrib); */
4887
  
unknown's avatar
unknown committed
4888 4889 4890
  DBUG_PRINT("quit",("Exiting main thread"));

#ifndef __WIN__
unknown's avatar
unknown committed
4891
#ifdef EXTRA_DEBUG2
unknown's avatar
unknown committed
4892 4893
  sql_print_error("Before Lock_thread_count");
#endif
Marc Alff's avatar
Marc Alff committed
4894
  mysql_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
4895
  DBUG_PRINT("quit", ("Got thread_count mutex"));
unknown's avatar
unknown committed
4896
  select_thread_in_use=0;			// For close_connections
Marc Alff's avatar
Marc Alff committed
4897 4898
  mysql_mutex_unlock(&LOCK_thread_count);
  mysql_cond_broadcast(&COND_thread_count);
unknown's avatar
unknown committed
4899
#ifdef EXTRA_DEBUG2
unknown's avatar
unknown committed
4900 4901
  sql_print_error("After lock_thread_count");
#endif
unknown's avatar
merge  
unknown committed
4902
#endif /* __WIN__ */
4903

unknown's avatar
unknown committed
4904
  /* Wait until cleanup is done */
Marc Alff's avatar
Marc Alff committed
4905
  mysql_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
4906
  while (!ready_to_exit)
Marc Alff's avatar
Marc Alff committed
4907 4908
    mysql_cond_wait(&COND_thread_count, &LOCK_thread_count);
  mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
merge  
unknown committed
4909 4910

#if defined(__WIN__) && !defined(EMBEDDED_LIBRARY)
unknown's avatar
merge  
unknown committed
4911 4912 4913 4914
  if (Service.IsNT() && start_mode)
    Service.Stop();
  else
  {
unknown's avatar
unknown committed
4915
    Service.SetShutdownEvent(0);
unknown's avatar
merge  
unknown committed
4916 4917 4918
    if (hEventShutdown)
      CloseHandle(hEventShutdown);
  }
unknown's avatar
unknown committed
4919
#endif
unknown's avatar
unknown committed
4920
  clean_up(1);
Marc Alff's avatar
Marc Alff committed
4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932
#ifdef HAVE_PSI_INTERFACE
  /*
    Disable the instrumentation, to avoid recording events
    during the shutdown.
  */
  if (PSI_server)
  {
    PSI_server->delete_current_thread();
    PSI_server= NULL;
  }
  shutdown_performance_schema();
#endif
4933
  mysqld_exit(0);
unknown's avatar
unknown committed
4934 4935
}

4936
#endif /* !EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
4937

unknown's avatar
SCRUM  
unknown committed
4938

4939 4940 4941 4942 4943
/****************************************************************************
  Main and thread entry function for Win32
  (all this is needed only to run mysqld as a service on WinNT)
****************************************************************************/

unknown's avatar
unknown committed
4944
#if defined(__WIN__) && !defined(EMBEDDED_LIBRARY)
unknown's avatar
unknown committed
4945 4946
int mysql_service(void *p)
{
4947 4948 4949 4950
  if (use_opt_args)
    win_main(opt_argc, opt_argv);
  else
    win_main(Service.my_argc, Service.my_argv);
unknown's avatar
unknown committed
4951 4952 4953
  return 0;
}

4954 4955 4956 4957 4958 4959 4960 4961

/* Quote string if it contains space, else copy */

static char *add_quoted_string(char *to, const char *from, char *to_end)
{
  uint length= (uint) (to_end-to);

  if (!strchr(from, ' '))
unknown's avatar
unknown committed
4962 4963
    return strmake(to, from, length-1);
  return strxnmov(to, length-1, "\"", from, "\"", NullS);
4964 4965 4966
}


unknown's avatar
unknown committed
4967 4968
/**
  Handle basic handling of services, like installation and removal.
4969

unknown's avatar
unknown committed
4970 4971 4972 4973 4974 4975 4976
  @param argv	   	        Pointer to argument list
  @param servicename		Internal name of service
  @param displayname		Display name of service (in taskbar ?)
  @param file_path		Path to this program
  @param startup_option	Startup option to mysqld

  @retval
4977
    0		option handled
unknown's avatar
unknown committed
4978
  @retval
4979
    1		Could not handle option
unknown's avatar
unknown committed
4980
*/
4981

4982 4983 4984 4985 4986
static bool
default_service_handling(char **argv,
			 const char *servicename,
			 const char *displayname,
			 const char *file_path,
unknown's avatar
Merge  
unknown committed
4987 4988
			 const char *extra_opt,
			 const char *account_name)
4989
{
4990
  char path_and_service[FN_REFLEN+FN_REFLEN+32], *pos, *end;
4991
  const char *opt_delim;
4992
  end= path_and_service + sizeof(path_and_service)-3;
4993 4994 4995 4996 4997

  /* We have to quote filename if it contains spaces */
  pos= add_quoted_string(path_and_service, file_path, end);
  if (*extra_opt)
  {
4998 4999 5000 5001 5002
    /* 
     Add option after file_path. There will be zero or one extra option.  It's 
     assumed to be --defaults-file=file but isn't checked.  The variable (not
     the option name) should be quoted if it contains a string.  
    */
5003
    *pos++= ' ';
5004 5005 5006
    if (opt_delim= strchr(extra_opt, '='))
    {
      size_t length= ++opt_delim - extra_opt;
5007
      pos= strnmov(pos, extra_opt, length);
5008 5009 5010 5011 5012
    }
    else
      opt_delim= extra_opt;
    
    pos= add_quoted_string(pos, opt_delim, end);
5013
  }
5014 5015
  /* We must have servicename last */
  *pos++= ' ';
unknown's avatar
unknown committed
5016
  (void) add_quoted_string(pos, servicename, end);
5017

5018 5019
  if (Service.got_service_option(argv, "install"))
  {
unknown's avatar
Merge  
unknown committed
5020 5021
    Service.Install(1, servicename, displayname, path_and_service,
                    account_name);
5022 5023 5024 5025
    return 0;
  }
  if (Service.got_service_option(argv, "install-manual"))
  {
unknown's avatar
Merge  
unknown committed
5026 5027
    Service.Install(0, servicename, displayname, path_and_service,
                    account_name);
5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038
    return 0;
  }
  if (Service.got_service_option(argv, "remove"))
  {
    Service.Remove(servicename);
    return 0;
  }
  return 1;
}


5039
int mysqld_main(int argc, char **argv)
unknown's avatar
unknown committed
5040
{
unknown's avatar
unknown committed
5041 5042 5043 5044
  /*
    When several instances are running on the same machine, we
    need to have an  unique  named  hEventShudown  through the
    application PID e.g.: MySQLShutdown1890; MySQLShutdown2342
unknown's avatar
Merge  
unknown committed
5045
  */
5046
  int10_to_str((int) GetCurrentProcessId(),strmov(shutdown_event_name,
unknown's avatar
Merge  
unknown committed
5047 5048
                                                  "MySQLShutdown"), 10);

5049 5050 5051
  /* Must be initialized early for comparison of service name */
  system_charset_info= &my_charset_utf8_general_ci;

unknown's avatar
unknown committed
5052
  if (Service.GetOS())	/* true NT family */
unknown's avatar
unknown committed
5053
  {
unknown's avatar
unknown committed
5054
    char file_path[FN_REFLEN];
5055
    my_path(file_path, argv[0], "");		      /* Find name in path */
unknown's avatar
unknown committed
5056 5057
    fn_format(file_path,argv[0],file_path,"",
	      MY_REPLACE_DIR | MY_UNPACK_FILENAME | MY_RESOLVE_SYMLINKS);
unknown's avatar
unknown committed
5058

unknown's avatar
unknown committed
5059
    if (argc == 2)
5060
    {
5061
      if (!default_service_handling(argv, MYSQL_SERVICENAME, MYSQL_SERVICENAME,
unknown's avatar
Merge  
unknown committed
5062
				   file_path, "", NULL))
5063
	return 0;
unknown's avatar
unknown committed
5064
      if (Service.IsService(argv[1]))        /* Start an optional service */
unknown's avatar
unknown committed
5065
      {
unknown's avatar
unknown committed
5066 5067 5068 5069 5070 5071
	/*
	  Only add the service name to the groups read from the config file
	  if it's not "MySQL". (The default service name should be 'mysqld'
	  but we started a bad tradition by calling it MySQL from the start
	  and we are now stuck with it.
	*/
5072
	if (my_strcasecmp(system_charset_info, argv[1],"mysql"))
5073
	  load_default_groups[load_default_groups_sz-2]= argv[1];
unknown's avatar
unknown committed
5074
        start_mode= 1;
5075
        Service.Init(argv[1], mysql_service);
unknown's avatar
unknown committed
5076 5077 5078 5079
        return 0;
      }
    }
    else if (argc == 3) /* install or remove any optional service */
unknown's avatar
unknown committed
5080
    {
unknown's avatar
Merge  
unknown committed
5081 5082
      if (!default_service_handling(argv, argv[2], argv[2], file_path, "",
                                    NULL))
5083 5084
	return 0;
      if (Service.IsService(argv[2]))
unknown's avatar
unknown committed
5085
      {
5086 5087 5088 5089
	/*
	  mysqld was started as
	  mysqld --defaults-file=my_path\my.ini service-name
	*/
5090
	use_opt_args=1;
5091
	opt_argc= 2;				// Skip service-name
5092 5093
	opt_argv=argv;
	start_mode= 1;
5094
	if (my_strcasecmp(system_charset_info, argv[2],"mysql"))
5095
	  load_default_groups[load_default_groups_sz-2]= argv[2];
5096
	Service.Init(argv[2], mysql_service);
5097
	return 0;
unknown's avatar
unknown committed
5098 5099
      }
    }
unknown's avatar
Merge  
unknown committed
5100
    else if (argc == 4 || argc == 5)
5101 5102
    {
      /*
unknown's avatar
Merge  
unknown committed
5103 5104 5105 5106 5107
        This may seem strange, because we handle --local-service while
        preserving 4.1's behavior of allowing any one other argument that is
        passed to the service on startup. (The assumption is that this is
        --defaults-file=file, but that was not enforced in 4.1, so we don't
        enforce it here.)
5108
      */
unknown's avatar
Merge  
unknown committed
5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123
      const char *extra_opt= NullS;
      const char *account_name = NullS;
      int index;
      for (index = 3; index < argc; index++)
      {
        if (!strcmp(argv[index], "--local-service"))
          account_name= "NT AUTHORITY\\LocalService";
        else
          extra_opt= argv[index];
      }

      if (argc == 4 || account_name)
        if (!default_service_handling(argv, argv[2], argv[2], file_path,
                                      extra_opt, account_name))
          return 0;
5124
    }
unknown's avatar
unknown committed
5125
    else if (argc == 1 && Service.IsService(MYSQL_SERVICENAME))
unknown's avatar
unknown committed
5126
    {
unknown's avatar
unknown committed
5127 5128 5129
      /* start the default service */
      start_mode= 1;
      Service.Init(MYSQL_SERVICENAME, mysql_service);
unknown's avatar
unknown committed
5130 5131 5132
      return 0;
    }
  }
unknown's avatar
unknown committed
5133
  /* Start as standalone server */
unknown's avatar
unknown committed
5134 5135 5136 5137 5138 5139 5140 5141
  Service.my_argc=argc;
  Service.my_argv=argv;
  mysql_service(NULL);
  return 0;
}
#endif


unknown's avatar
unknown committed
5142
/**
5143 5144 5145
  Execute all commands from a file. Used by the mysql_install_db script to
  create MySQL privilege tables without having to start a full MySQL server.
*/
5146

Marc Alff's avatar
Marc Alff committed
5147
static void bootstrap(MYSQL_FILE *file)
unknown's avatar
unknown committed
5148
{
5149
  DBUG_ENTER("bootstrap");
5150

5151
  THD *thd= new THD;
unknown's avatar
unknown committed
5152
  thd->bootstrap=1;
unknown's avatar
unknown committed
5153
  my_net_init(&thd->net,(st_vio*) 0);
unknown's avatar
unknown committed
5154
  thd->max_client_packet_length= thd->net.max_packet;
5155
  thd->security_ctx->master_access= ~(ulong)0;
unknown's avatar
unknown committed
5156
  thd->thread_id= thd->variables.pseudo_thread_id= thread_id++;
unknown's avatar
unknown committed
5157
  thread_count++;
5158
  in_bootstrap= TRUE;
5159 5160

  bootstrap_file=file;
unknown's avatar
unknown committed
5161
#ifndef EMBEDDED_LIBRARY			// TODO:  Enable this
Marc Alff's avatar
Marc Alff committed
5162 5163 5164
  if (mysql_thread_create(key_thread_bootstrap,
                          &thd->real_id, &connection_attrib, handle_bootstrap,
                          (void*) thd))
5165
  {
5166
    sql_print_warning("Can't create thread to handle bootstrap");
unknown's avatar
Merge  
unknown committed
5167 5168
    bootstrap_error=-1;
    DBUG_VOID_RETURN;
5169 5170
  }
  /* Wait for thread to die */
Marc Alff's avatar
Marc Alff committed
5171
  mysql_mutex_lock(&LOCK_thread_count);
5172
  while (in_bootstrap)
5173
  {
Marc Alff's avatar
Marc Alff committed
5174
    mysql_cond_wait(&COND_thread_count, &LOCK_thread_count);
5175 5176
    DBUG_PRINT("quit",("One thread died (count=%u)",thread_count));
  }
Marc Alff's avatar
Marc Alff committed
5177
  mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
5178 5179
#else
  thd->mysql= 0;
Marc Alff's avatar
Marc Alff committed
5180
  do_handle_bootstrap(thd);
unknown's avatar
unknown committed
5181 5182
#endif

unknown's avatar
Merge  
unknown committed
5183
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
5184 5185
}

5186

unknown's avatar
unknown committed
5187 5188
static bool read_init_file(char *file_name)
{
Marc Alff's avatar
Marc Alff committed
5189
  MYSQL_FILE *file;
unknown's avatar
unknown committed
5190 5191
  DBUG_ENTER("read_init_file");
  DBUG_PRINT("enter",("name: %s",file_name));
Marc Alff's avatar
Marc Alff committed
5192 5193
  if (!(file= mysql_file_fopen(key_file_init, file_name,
                               O_RDONLY, MYF(MY_WME))))
5194
    DBUG_RETURN(TRUE);
unknown's avatar
Merge  
unknown committed
5195
  bootstrap(file);
Marc Alff's avatar
Marc Alff committed
5196
  mysql_file_fclose(file, MYF(MY_WME));
5197
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
5198 5199 5200
}


5201
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
5202 5203 5204 5205 5206 5207 5208 5209 5210 5211

/*
   Simple scheduler that use the main thread to handle the request

   NOTES
     This is only used for debugging, when starting mysqld with
     --thread-handling=no-threads or --one-thread

     When we enter this function, LOCK_thread_count is hold!
*/
5212

unknown's avatar
unknown committed
5213 5214
void handle_connection_in_main_thread(THD *thd)
{
Marc Alff's avatar
Marc Alff committed
5215
  mysql_mutex_assert_owner(&LOCK_thread_count);
unknown's avatar
unknown committed
5216 5217
  thread_cache_size=0;			// Safety
  threads.append(thd);
Marc Alff's avatar
Marc Alff committed
5218
  mysql_mutex_unlock(&LOCK_thread_count);
5219
  thd->start_utime= my_micro_time();
Marc Alff's avatar
Marc Alff committed
5220
  do_handle_one_connection(thd);
unknown's avatar
unknown committed
5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234
}


/*
  Scheduler that uses one thread per connection
*/

void create_thread_to_handle_connection(THD *thd)
{
  if (cached_thread_count > wake_thread)
  {
    /* Get thread from cache */
    thread_cache.append(thd);
    wake_thread++;
Marc Alff's avatar
Marc Alff committed
5235
    mysql_cond_signal(&COND_thread_cache);
unknown's avatar
unknown committed
5236 5237 5238
  }
  else
  {
5239
    char error_message_buff[MYSQL_ERRMSG_SIZE];
unknown's avatar
unknown committed
5240 5241 5242 5243 5244
    /* Create new thread to handle connection */
    int error;
    thread_created++;
    threads.append(thd);
    DBUG_PRINT("info",(("creating thread %lu"), thd->thread_id));
5245
    thd->prior_thr_create_utime= thd->start_utime= my_micro_time();
Marc Alff's avatar
Marc Alff committed
5246 5247 5248 5249
    if ((error= mysql_thread_create(key_thread_one_connection,
                                    &thd->real_id, &connection_attrib,
                                    handle_one_connection,
                                    (void*) thd)))
unknown's avatar
unknown committed
5250
    {
5251
      /* purecov: begin inspected */
unknown's avatar
unknown committed
5252 5253 5254 5255 5256
      DBUG_PRINT("error",
                 ("Can't create thread to handle request (error %d)",
                  error));
      thread_count--;
      thd->killed= THD::KILL_CONNECTION;			// Safety
Marc Alff's avatar
Marc Alff committed
5257
      mysql_mutex_unlock(&LOCK_thread_count);
5258

Marc Alff's avatar
Marc Alff committed
5259
      mysql_mutex_lock(&LOCK_connection_count);
5260
      --connection_count;
Marc Alff's avatar
Marc Alff committed
5261
      mysql_mutex_unlock(&LOCK_connection_count);
5262

unknown's avatar
unknown committed
5263
      statistic_increment(aborted_connects,&LOCK_status);
5264 5265 5266
      /* Can't use my_error() since store_globals has not been called. */
      my_snprintf(error_message_buff, sizeof(error_message_buff),
                  ER(ER_CANT_CREATE_THREAD), error);
Marc Alff's avatar
Marc Alff committed
5267
      net_send_error(thd, ER_CANT_CREATE_THREAD, error_message_buff, NULL);
Marc Alff's avatar
Marc Alff committed
5268
      mysql_mutex_lock(&LOCK_thread_count);
unknown's avatar
unknown committed
5269 5270
      close_connection(thd,0,0);
      delete thd;
Marc Alff's avatar
Marc Alff committed
5271
      mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
5272 5273 5274 5275
      return;
      /* purecov: end */
    }
  }
Marc Alff's avatar
Marc Alff committed
5276
  mysql_mutex_unlock(&LOCK_thread_count);
unknown's avatar
unknown committed
5277 5278 5279 5280
  DBUG_PRINT("info",("Thread created"));
}


unknown's avatar
unknown committed
5281
/**
5282 5283 5284 5285 5286 5287
  Create new thread to handle incoming connection.

    This function will create new thread to handle the incoming
    connection.  If there are idle cached threads one will be used.
    'thd' will be pushed into 'threads'.

unknown's avatar
unknown committed
5288
    In single-threaded mode (\#define ONE_THREAD) connection will be
5289 5290
    handled inside this function.

unknown's avatar
unknown committed
5291
  @param[in,out] thd    Thread handle of future thread.
5292 5293
*/

unknown's avatar
unknown committed
5294 5295 5296 5297
static void create_new_thread(THD *thd)
{
  DBUG_ENTER("create_new_thread");

5298 5299 5300 5301 5302
  /*
    Don't allow too many connections. We roughly check here that we allow
    only (max_connections + 1) connections.
  */

Marc Alff's avatar
Marc Alff committed
5303
  mysql_mutex_lock(&LOCK_connection_count);
5304 5305

  if (connection_count >= max_connections + 1 || abort_loop)
unknown's avatar
unknown committed
5306
  {
Marc Alff's avatar
Marc Alff committed
5307
    mysql_mutex_unlock(&LOCK_connection_count);
5308

unknown's avatar
unknown committed
5309
    DBUG_PRINT("error",("Too many connections"));
5310
    close_connection(thd, ER_CON_COUNT_ERROR, 1);
unknown's avatar
unknown committed
5311 5312 5313
    delete thd;
    DBUG_VOID_RETURN;
  }
5314 5315 5316

  ++connection_count;

5317 5318 5319
  if (connection_count > max_used_connections)
    max_used_connections= connection_count;

Marc Alff's avatar
Marc Alff committed
5320
  mysql_mutex_unlock(&LOCK_connection_count);
5321 5322 5323

  /* Start a new thread to handle connection. */

Marc Alff's avatar
Marc Alff committed
5324
  mysql_mutex_lock(&LOCK_thread_count);
5325

5326 5327 5328 5329 5330
  /*
    The initialization of thread_id is done in create_embedded_thd() for
    the embedded library.
    TODO: refactor this to avoid code duplication there
  */
unknown's avatar
unknown committed
5331
  thd->thread_id= thd->variables.pseudo_thread_id= thread_id++;
unknown's avatar
unknown committed
5332

5333 5334
  thread_count++;

unknown's avatar
unknown committed
5335
  thread_scheduler.add_connection(thd);
5336

unknown's avatar
unknown committed
5337 5338
  DBUG_VOID_RETURN;
}
5339 5340
#endif /* EMBEDDED_LIBRARY */

unknown's avatar
unknown committed
5341

unknown's avatar
unknown committed
5342 5343 5344 5345
#ifdef SIGNALS_DONT_BREAK_READ
inline void kill_broken_server()
{
  /* hack to get around signals ignored in syscalls for problem OS's */
unknown's avatar
unknown committed
5346 5347 5348 5349
  if (
#if !defined(__NETWARE__)
      unix_sock == INVALID_SOCKET ||
#endif
5350
      (!opt_disable_networking && ip_sock == INVALID_SOCKET))
unknown's avatar
unknown committed
5351 5352
  {
    select_thread_in_use = 0;
unknown's avatar
unknown committed
5353 5354
    /* The following call will never return */
    kill_server(IF_NETWARE(MYSQL_KILL_SIGNAL, (void*) MYSQL_KILL_SIGNAL));
unknown's avatar
unknown committed
5355 5356 5357 5358 5359 5360
  }
}
#define MAYBE_BROKEN_SYSCALL kill_broken_server();
#else
#define MAYBE_BROKEN_SYSCALL
#endif
unknown's avatar
unknown committed
5361 5362 5363

	/* Handle new connections and spawn new process to handle them */

5364
#ifndef EMBEDDED_LIBRARY
5365

5366
void handle_connections_sockets()
unknown's avatar
unknown committed
5367
{
5368
  my_socket UNINIT_VAR(sock), UNINIT_VAR(new_sock);
unknown's avatar
unknown committed
5369 5370
  uint error_count=0;
  THD *thd;
5371
  struct sockaddr_storage cAddr;
5372
  int ip_flags=0,socket_flags=0,flags=0,retval;
unknown's avatar
unknown committed
5373
  st_vio *vio_tmp;
5374 5375 5376 5377 5378 5379 5380 5381
#ifdef HAVE_POLL
  int socket_count= 0;
  struct pollfd fds[2]; // for ip_sock and unix_sock
#else
  fd_set readFDs,clientFDs;
  uint max_used_connection= (uint) (max(ip_sock,unix_sock)+1);
#endif

unknown's avatar
unknown committed
5382 5383
  DBUG_ENTER("handle_connections_sockets");

5384
#ifndef HAVE_POLL
unknown's avatar
unknown committed
5385
  FD_ZERO(&clientFDs);
5386 5387
#endif

unknown's avatar
unknown committed
5388 5389
  if (ip_sock != INVALID_SOCKET)
  {
5390 5391 5392 5393 5394
#ifdef HAVE_POLL
    fds[socket_count].fd= ip_sock;
    fds[socket_count].events= POLLIN;
    socket_count++;
#else
unknown's avatar
unknown committed
5395
    FD_SET(ip_sock,&clientFDs);
5396
#endif    
unknown's avatar
unknown committed
5397 5398 5399 5400 5401
#ifdef HAVE_FCNTL
    ip_flags = fcntl(ip_sock, F_GETFL, 0);
#endif
  }
#ifdef HAVE_SYS_UN_H
5402 5403 5404 5405 5406
#ifdef HAVE_POLL
  fds[socket_count].fd= unix_sock;
  fds[socket_count].events= POLLIN;
  socket_count++;
#else
unknown's avatar
unknown committed
5407
  FD_SET(unix_sock,&clientFDs);
5408
#endif
unknown's avatar
unknown committed
5409
#ifdef HAVE_FCNTL
unknown's avatar
unknown committed
5410
  socket_flags=fcntl(unix_sock, F_GETFL, 0);
unknown's avatar
unknown committed
5411
#endif
unknown's avatar
unknown committed
5412 5413 5414
#endif

  DBUG_PRINT("general",("Waiting for connections."));
unknown's avatar
unknown committed
5415
  MAYBE_BROKEN_SYSCALL;
unknown's avatar
unknown committed
5416 5417
  while (!abort_loop)
  {
5418 5419
#ifdef HAVE_POLL
    retval= poll(fds, socket_count, -1);
unknown's avatar
unknown committed
5420
#else
5421 5422 5423 5424 5425 5426
    readFDs=clientFDs;

    retval= select((int) max_used_connection,&readFDs,0,0,0);
#endif

    if (retval < 0)
unknown's avatar
unknown committed
5427
    {
unknown's avatar
unknown committed
5428
      if (socket_errno != SOCKET_EINTR)
unknown's avatar
unknown committed
5429 5430
      {
	if (!select_errors++ && !abort_loop)	/* purecov: inspected */
unknown's avatar
unknown committed
5431
	  sql_print_error("mysqld: Got error %d from select",socket_errno); /* purecov: inspected */
unknown's avatar
unknown committed
5432
      }
unknown's avatar
unknown committed
5433
      MAYBE_BROKEN_SYSCALL
unknown's avatar
unknown committed
5434 5435
      continue;
    }
5436

unknown's avatar
unknown committed
5437
    if (abort_loop)
unknown's avatar
unknown committed
5438 5439
    {
      MAYBE_BROKEN_SYSCALL;
unknown's avatar
unknown committed
5440
      break;
unknown's avatar
unknown committed
5441
    }
unknown's avatar
unknown committed
5442

5443
    /* Is this a new connection request ? */
5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458
#ifdef HAVE_POLL
    for (int i= 0; i < socket_count; ++i) 
    {
      if (fds[i].revents & POLLIN)
      {
        sock= fds[i].fd;
#ifdef HAVE_FCNTL
        flags= fcntl(sock, F_GETFL, 0);
#else
        flags= 0;
#endif // HAVE_FCNTL
        break;
      }
    }
#else  // HAVE_POLL
unknown's avatar
unknown committed
5459 5460 5461 5462 5463 5464 5465
#ifdef HAVE_SYS_UN_H
    if (FD_ISSET(unix_sock,&readFDs))
    {
      sock = unix_sock;
      flags= socket_flags;
    }
    else
5466
#endif // HAVE_SYS_UN_H
unknown's avatar
unknown committed
5467 5468 5469 5470
    {
      sock = ip_sock;
      flags= ip_flags;
    }
5471
#endif // HAVE_POLL
unknown's avatar
unknown committed
5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484

#if !defined(NO_FCNTL_NONBLOCK)
    if (!(test_flags & TEST_BLOCKING))
    {
#if defined(O_NONBLOCK)
      fcntl(sock, F_SETFL, flags | O_NONBLOCK);
#elif defined(O_NDELAY)
      fcntl(sock, F_SETFL, flags | O_NDELAY);
#endif
    }
#endif /* NO_FCNTL_NONBLOCK */
    for (uint retry=0; retry < MAX_ACCEPT_RETRY; retry++)
    {
5485 5486 5487
      size_socket length= sizeof(struct sockaddr_storage);
      new_sock= accept(sock, (struct sockaddr *)(&cAddr),
                       &length);
unknown's avatar
unknown committed
5488 5489 5490 5491 5492 5493 5494
#ifdef __NETWARE__ 
      // TODO: temporary fix, waiting for TCP/IP fix - DEFECT000303149
      if ((new_sock == INVALID_SOCKET) && (socket_errno == EINVAL))
      {
        kill_server(SIGTERM);
      }
#endif
unknown's avatar
unknown committed
5495 5496
      if (new_sock != INVALID_SOCKET ||
	  (socket_errno != SOCKET_EINTR && socket_errno != SOCKET_EAGAIN))
unknown's avatar
unknown committed
5497
	break;
unknown's avatar
unknown committed
5498
      MAYBE_BROKEN_SYSCALL;
unknown's avatar
unknown committed
5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510
#if !defined(NO_FCNTL_NONBLOCK)
      if (!(test_flags & TEST_BLOCKING))
      {
	if (retry == MAX_ACCEPT_RETRY - 1)
	  fcntl(sock, F_SETFL, flags);		// Try without O_NONBLOCK
      }
#endif
    }
#if !defined(NO_FCNTL_NONBLOCK)
    if (!(test_flags & TEST_BLOCKING))
      fcntl(sock, F_SETFL, flags);
#endif
unknown's avatar
unknown committed
5511
    if (new_sock == INVALID_SOCKET)
unknown's avatar
unknown committed
5512 5513 5514
    {
      if ((error_count++ & 255) == 0)		// This can happen often
	sql_perror("Error in accept");
unknown's avatar
unknown committed
5515
      MAYBE_BROKEN_SYSCALL;
unknown's avatar
unknown committed
5516
      if (socket_errno == SOCKET_ENFILE || socket_errno == SOCKET_EMFILE)
unknown's avatar
unknown committed
5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527
	sleep(1);				// Give other threads some time
      continue;
    }

#ifdef HAVE_LIBWRAP
    {
      if (sock == ip_sock)
      {
	struct request_info req;
	signal(SIGCHLD, SIG_DFL);
	request_init(&req, RQ_DAEMON, libwrapName, RQ_FILE, new_sock, NULL);
5528 5529
	my_fromhost(&req);
	if (!my_hosts_access(&req))
unknown's avatar
unknown committed
5530
	{
unknown's avatar
unknown committed
5531 5532 5533 5534 5535
	  /*
	    This may be stupid but refuse() includes an exit(0)
	    which we surely don't want...
	    clean_exit() - same stupid thing ...
	  */
5536
	  syslog(deny_severity, "refused connect from %s",
5537
		 my_eval_client(&req));
unknown's avatar
unknown committed
5538

unknown's avatar
unknown committed
5539 5540 5541 5542 5543 5544
	  /*
	    C++ sucks (the gibberish in front just translates the supplied
	    sink function pointer in the req structure from a void (*sink)();
	    to a void(*sink)(int) if you omit the cast, the C++ compiler
	    will cry...
	  */
unknown's avatar
unknown committed
5545 5546 5547
	  if (req.sink)
	    ((void (*)(int))req.sink)(req.fd);

5548
	  (void) shutdown(new_sock, SHUT_RDWR);
unknown's avatar
unknown committed
5549 5550 5551 5552 5553 5554 5555 5556 5557
	  (void) closesocket(new_sock);
	  continue;
	}
      }
    }
#endif /* HAVE_LIBWRAP */

    {
      size_socket dummyLen;
5558 5559 5560 5561
      struct sockaddr_storage dummy;
      dummyLen = sizeof(dummy);
      if (  getsockname(new_sock,(struct sockaddr *)&dummy, 
                  (SOCKET_SIZE_TYPE *)&dummyLen) < 0  )
unknown's avatar
unknown committed
5562 5563
      {
	sql_perror("Error on new connection socket");
5564
	(void) shutdown(new_sock, SHUT_RDWR);
unknown's avatar
unknown committed
5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575
	(void) closesocket(new_sock);
	continue;
      }
    }

    /*
    ** Don't allow too many connections
    */

    if (!(thd= new THD))
    {
5576
      (void) shutdown(new_sock, SHUT_RDWR);
Konstantin Osipov's avatar
Konstantin Osipov committed
5577
      (void) closesocket(new_sock);
unknown's avatar
unknown committed
5578 5579 5580
      continue;
    }
    if (!(vio_tmp=vio_new(new_sock,
5581
			  sock == unix_sock ? VIO_TYPE_SOCKET :
unknown's avatar
unknown committed
5582
			  VIO_TYPE_TCPIP,
5583
			  sock == unix_sock ? VIO_LOCALHOST: 0)) ||
unknown's avatar
unknown committed
5584 5585
	my_net_init(&thd->net,vio_tmp))
    {
5586 5587 5588 5589 5590 5591 5592
      /*
        Only delete the temporary vio if we didn't already attach it to the
        NET object. The destructor in THD will delete any initialized net
        structure.
      */
      if (vio_tmp && thd->net.vio != vio_tmp)
        vio_delete(vio_tmp);
unknown's avatar
unknown committed
5593 5594
      else
      {
5595
	(void) shutdown(new_sock, SHUT_RDWR);
unknown's avatar
unknown committed
5596 5597 5598 5599 5600 5601
	(void) closesocket(new_sock);
      }
      delete thd;
      continue;
    }
    if (sock == unix_sock)
5602
      thd->security_ctx->host=(char*) my_localhost;
5603

unknown's avatar
unknown committed
5604 5605
    create_new_thread(thd);
  }
5606 5607 5608
  DBUG_VOID_RETURN;
}

unknown's avatar
unknown committed
5609

5610 5611 5612 5613 5614
#ifdef _WIN32
pthread_handler_t handle_connections_sockets_thread(void *arg)
{
  my_thread_init();
  handle_connections_sockets();
5615
  decrement_handler_count();
5616
  return 0;
unknown's avatar
unknown committed
5617 5618
}

5619
pthread_handler_t handle_connections_namedpipes(void *arg)
unknown's avatar
unknown committed
5620 5621
{
  HANDLE hConnectedPipe;
5622
  OVERLAPPED connectOverlapped= {0};
unknown's avatar
unknown committed
5623 5624 5625
  THD *thd;
  my_thread_init();
  DBUG_ENTER("handle_connections_namedpipes");
5626 5627 5628 5629 5630 5631
  connectOverlapped.hEvent= CreateEvent(NULL, TRUE, FALSE, NULL);
  if (!connectOverlapped.hEvent)
  {
    sql_print_error("Can't create event, last error=%u", GetLastError());
    unireg_abort(1);
  }
unknown's avatar
unknown committed
5632 5633 5634 5635
  DBUG_PRINT("general",("Waiting for named pipe connections."));
  while (!abort_loop)
  {
    /* wait for named pipe connection */
5636 5637 5638 5639 5640 5641 5642 5643 5644 5645
    BOOL fConnected= ConnectNamedPipe(hPipe, &connectOverlapped);
    if (!fConnected && (GetLastError() == ERROR_IO_PENDING))
    {
        /*
          ERROR_IO_PENDING says async IO has started but not yet finished.
          GetOverlappedResult will wait for completion.
        */
        DWORD bytes;
        fConnected= GetOverlappedResult(hPipe, &connectOverlapped,&bytes, TRUE);
    }
unknown's avatar
unknown committed
5646 5647
    if (abort_loop)
      break;
unknown's avatar
unknown committed
5648
    if (!fConnected)
unknown's avatar
unknown committed
5649
      fConnected = GetLastError() == ERROR_PIPE_CONNECTED;
unknown's avatar
unknown committed
5650
    if (!fConnected)
unknown's avatar
unknown committed
5651
    {
unknown's avatar
Merge  
unknown committed
5652 5653
      CloseHandle(hPipe);
      if ((hPipe= CreateNamedPipe(pipe_name,
5654 5655
                                  PIPE_ACCESS_DUPLEX |
                                  FILE_FLAG_OVERLAPPED,
unknown's avatar
Merge  
unknown committed
5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666
                                  PIPE_TYPE_BYTE |
                                  PIPE_READMODE_BYTE |
                                  PIPE_WAIT,
                                  PIPE_UNLIMITED_INSTANCES,
                                  (int) global_system_variables.
                                  net_buffer_length,
                                  (int) global_system_variables.
                                  net_buffer_length,
                                  NMPWAIT_USE_DEFAULT_WAIT,
                                  &saPipeSecurity)) ==
	  INVALID_HANDLE_VALUE)
unknown's avatar
unknown committed
5667 5668 5669 5670 5671 5672 5673
      {
	sql_perror("Can't create new named pipe!");
	break;					// Abort
      }
    }
    hConnectedPipe = hPipe;
    /* create new pipe for new connection */
5674
    if ((hPipe = CreateNamedPipe(pipe_name,
5675 5676
                 PIPE_ACCESS_DUPLEX |
                 FILE_FLAG_OVERLAPPED,
unknown's avatar
unknown committed
5677 5678 5679 5680
				 PIPE_TYPE_BYTE |
				 PIPE_READMODE_BYTE |
				 PIPE_WAIT,
				 PIPE_UNLIMITED_INSTANCES,
5681 5682
				 (int) global_system_variables.net_buffer_length,
				 (int) global_system_variables.net_buffer_length,
unknown's avatar
unknown committed
5683 5684 5685 5686 5687 5688 5689 5690 5691
				 NMPWAIT_USE_DEFAULT_WAIT,
				 &saPipeSecurity)) ==
	INVALID_HANDLE_VALUE)
    {
      sql_perror("Can't create new named pipe!");
      hPipe=hConnectedPipe;
      continue;					// We have to try again
    }

unknown's avatar
unknown committed
5692
    if (!(thd = new THD))
unknown's avatar
unknown committed
5693
    {
unknown's avatar
Merge  
unknown committed
5694 5695
      DisconnectNamedPipe(hConnectedPipe);
      CloseHandle(hConnectedPipe);
unknown's avatar
unknown committed
5696 5697
      continue;
    }
5698
    if (!(thd->net.vio= vio_new_win32pipe(hConnectedPipe)) ||
unknown's avatar
unknown committed
5699 5700
	my_net_init(&thd->net, thd->net.vio))
    {
5701
      close_connection(thd, ER_OUT_OF_RESOURCES, 1);
unknown's avatar
unknown committed
5702 5703 5704
      delete thd;
      continue;
    }
5705 5706
    /* Host is unknown */
    thd->security_ctx->host= my_strdup(my_localhost, MYF(0));
unknown's avatar
unknown committed
5707 5708
    create_new_thread(thd);
  }
5709
  CloseHandle(connectOverlapped.hEvent);
5710
  DBUG_LEAVE;
5711
  decrement_handler_count();
5712
  return 0;
unknown's avatar
unknown committed
5713
}
Vladislav Vaintroub's avatar
Vladislav Vaintroub committed
5714
#endif /* _WIN32 */
unknown's avatar
unknown committed
5715

5716

unknown's avatar
unknown committed
5717
#ifdef HAVE_SMEM
5718

unknown's avatar
unknown committed
5719 5720
/**
  Thread of shared memory's service.
5721

unknown's avatar
unknown committed
5722 5723
  @param arg                              Arguments of thread
*/
5724
pthread_handler_t handle_connections_shared_memory(void *arg)
5725
{
5726 5727
  /* file-mapping object, use for create shared memory */
  HANDLE handle_connect_file_map= 0;
5728
  char  *handle_connect_map= 0;                 // pointer on shared memory
5729 5730 5731
  HANDLE event_connect_answer= 0;
  ulong smem_buffer_length= shared_memory_buffer_length + 4;
  ulong connect_number= 1;
5732
  char *tmp= NULL;
5733 5734
  char *suffix_pos;
  char connect_number_char[22], *p;
5735
  const char *errmsg= 0;
5736
  SECURITY_ATTRIBUTES *sa_event= 0, *sa_mapping= 0;
5737 5738 5739 5740
  my_thread_init();
  DBUG_ENTER("handle_connections_shared_memorys");
  DBUG_PRINT("general",("Waiting for allocated shared memory."));

5741 5742 5743 5744 5745 5746
  /*
     get enough space base-name + '_' + longest suffix we might ever send
   */
  if (!(tmp= (char *)my_malloc(strlen(shared_memory_base_name) + 32L, MYF(MY_FAE))))
    goto error;

5747 5748 5749 5750 5751 5752 5753 5754
  if (my_security_attr_create(&sa_event, &errmsg,
                              GENERIC_ALL, SYNCHRONIZE | EVENT_MODIFY_STATE))
    goto error;

  if (my_security_attr_create(&sa_mapping, &errmsg,
                             GENERIC_ALL, FILE_MAP_READ | FILE_MAP_WRITE))
    goto error;

5755 5756 5757 5758 5759 5760 5761
  /*
    The name of event and file-mapping events create agree next rule:
      shared_memory_base_name+unique_part
    Where:
      shared_memory_base_name is unique value for each server
      unique_part is unique value for each object (events and file-mapping)
  */
5762
  suffix_pos= strxmov(tmp,shared_memory_base_name,"_",NullS);
5763
  strmov(suffix_pos, "CONNECT_REQUEST");
5764 5765
  if ((smem_event_connect_request= CreateEvent(sa_event,
                                               FALSE, FALSE, tmp)) == 0)
5766
  {
5767
    errmsg= "Could not create request event";
5768 5769
    goto error;
  }
5770
  strmov(suffix_pos, "CONNECT_ANSWER");
5771
  if ((event_connect_answer= CreateEvent(sa_event, FALSE, FALSE, tmp)) == 0)
5772
  {
5773
    errmsg="Could not create answer event";
5774 5775
    goto error;
  }
5776
  strmov(suffix_pos, "CONNECT_DATA");
5777 5778 5779
  if ((handle_connect_file_map=
       CreateFileMapping(INVALID_HANDLE_VALUE, sa_mapping,
                         PAGE_READWRITE, 0, sizeof(connect_number), tmp)) == 0)
5780
  {
5781
    errmsg= "Could not create file mapping";
5782 5783
    goto error;
  }
5784 5785 5786
  if ((handle_connect_map= (char *)MapViewOfFile(handle_connect_file_map,
						  FILE_MAP_WRITE,0,0,
						  sizeof(DWORD))) == 0)
5787
  {
5788
    errmsg= "Could not create shared memory service";
5789 5790 5791 5792 5793
    goto error;
  }

  while (!abort_loop)
  {
5794
    /* Wait a request from client */
5795
    WaitForSingleObject(smem_event_connect_request,INFINITE);
5796

unknown's avatar
unknown committed
5797 5798 5799
    /*
       it can be after shutdown command
    */
unknown's avatar
Merge  
unknown committed
5800
    if (abort_loop)
unknown's avatar
unknown committed
5801
      goto error;
5802

5803 5804 5805 5806 5807 5808
    HANDLE handle_client_file_map= 0;
    char  *handle_client_map= 0;
    HANDLE event_client_wrote= 0;
    HANDLE event_client_read= 0;    // for transfer data server <-> client
    HANDLE event_server_wrote= 0;
    HANDLE event_server_read= 0;
unknown's avatar
unknown committed
5809
    HANDLE event_conn_closed= 0;
5810
    THD *thd= 0;
5811

5812
    p= int10_to_str(connect_number, connect_number_char, 10);
5813 5814 5815 5816 5817 5818 5819 5820 5821 5822
    /*
      The name of event and file-mapping events create agree next rule:
        shared_memory_base_name+unique_part+number_of_connection
        Where:
	  shared_memory_base_name is uniquel value for each server
	  unique_part is unique value for each object (events and file-mapping)
	  number_of_connection is connection-number between server and client
    */
    suffix_pos= strxmov(tmp,shared_memory_base_name,"_",connect_number_char,
			 "_",NullS);
5823
    strmov(suffix_pos, "DATA");
5824 5825 5826
    if ((handle_client_file_map=
         CreateFileMapping(INVALID_HANDLE_VALUE, sa_mapping,
                           PAGE_READWRITE, 0, smem_buffer_length, tmp)) == 0)
5827
    {
5828
      errmsg= "Could not create file mapping";
5829 5830
      goto errorconn;
    }
5831 5832 5833
    if ((handle_client_map= (char*)MapViewOfFile(handle_client_file_map,
						  FILE_MAP_WRITE,0,0,
						  smem_buffer_length)) == 0)
5834
    {
5835
      errmsg= "Could not create memory map";
5836 5837 5838
      goto errorconn;
    }
    strmov(suffix_pos, "CLIENT_WROTE");
5839
    if ((event_client_wrote= CreateEvent(sa_event, FALSE, FALSE, tmp)) == 0)
5840
    {
5841
      errmsg= "Could not create client write event";
5842 5843 5844
      goto errorconn;
    }
    strmov(suffix_pos, "CLIENT_READ");
5845
    if ((event_client_read= CreateEvent(sa_event, FALSE, FALSE, tmp)) == 0)
5846
    {
5847
      errmsg= "Could not create client read event";
5848 5849 5850
      goto errorconn;
    }
    strmov(suffix_pos, "SERVER_READ");
5851
    if ((event_server_read= CreateEvent(sa_event, FALSE, FALSE, tmp)) == 0)
5852
    {
5853
      errmsg= "Could not create server read event";
5854 5855 5856
      goto errorconn;
    }
    strmov(suffix_pos, "SERVER_WROTE");
5857 5858
    if ((event_server_wrote= CreateEvent(sa_event,
                                         FALSE, FALSE, tmp)) == 0)
5859
    {
5860
      errmsg= "Could not create server write event";
5861 5862
      goto errorconn;
    }
unknown's avatar
unknown committed
5863
    strmov(suffix_pos, "CONNECTION_CLOSED");
5864 5865
    if ((event_conn_closed= CreateEvent(sa_event,
                                        TRUE, FALSE, tmp)) == 0)
unknown's avatar
unknown committed
5866 5867 5868 5869
    {
      errmsg= "Could not create closed connection event";
      goto errorconn;
    }
5870
    if (abort_loop)
5871
      goto errorconn;
5872 5873 5874
    if (!(thd= new THD))
      goto errorconn;
    /* Send number of connection to client */
5875
    int4store(handle_connect_map, connect_number);
5876
    if (!SetEvent(event_connect_answer))
5877
    {
5878
      errmsg= "Could not send answer event";
5879 5880
      goto errorconn;
    }
5881
    /* Set event that client should receive data */
5882 5883
    if (!SetEvent(event_client_read))
    {
5884
      errmsg= "Could not set client to read mode";
5885 5886
      goto errorconn;
    }
5887
    if (!(thd->net.vio= vio_new_win32shared_memory(handle_client_file_map,
unknown's avatar
unknown committed
5888 5889 5890 5891 5892
                                                   handle_client_map,
                                                   event_client_wrote,
                                                   event_client_read,
                                                   event_server_wrote,
                                                   event_server_read,
unknown's avatar
unknown committed
5893
                                                   event_conn_closed)) ||
unknown's avatar
unknown committed
5894
                        my_net_init(&thd->net, thd->net.vio))
5895
    {
5896
      close_connection(thd, ER_OUT_OF_RESOURCES, 1);
5897 5898
      errmsg= 0;
      goto errorconn;
5899
    }
5900
    thd->security_ctx->host= my_strdup(my_localhost, MYF(0)); /* Host is unknown */
5901
    create_new_thread(thd);
5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913
    connect_number++;
    continue;

errorconn:
    /* Could not form connection;  Free used handlers/memort and retry */
    if (errmsg)
    {
      char buff[180];
      strxmov(buff, "Can't create shared memory connection: ", errmsg, ".",
	      NullS);
      sql_perror(buff);
    }
5914
    if (handle_client_file_map)
unknown's avatar
unknown committed
5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927
      CloseHandle(handle_client_file_map);
    if (handle_client_map)
      UnmapViewOfFile(handle_client_map);
    if (event_server_wrote)
      CloseHandle(event_server_wrote);
    if (event_server_read)
      CloseHandle(event_server_read);
    if (event_client_wrote)
      CloseHandle(event_client_wrote);
    if (event_client_read)
      CloseHandle(event_client_read);
    if (event_conn_closed)
      CloseHandle(event_conn_closed);
5928
    delete thd;
5929
  }
5930 5931

  /* End shared memory handling */
5932
error:
5933 5934 5935
  if (tmp)
    my_free(tmp, MYF(0));

5936 5937 5938 5939 5940 5941
  if (errmsg)
  {
    char buff[180];
    strxmov(buff, "Can't create shared memory service: ", errmsg, ".", NullS);
    sql_perror(buff);
  }
5942 5943
  my_security_attr_free(sa_event);
  my_security_attr_free(sa_mapping);
5944 5945 5946
  if (handle_connect_map)	UnmapViewOfFile(handle_connect_map);
  if (handle_connect_file_map)	CloseHandle(handle_connect_file_map);
  if (event_connect_answer)	CloseHandle(event_connect_answer);
5947
  if (smem_event_connect_request) CloseHandle(smem_event_connect_request);
5948
  DBUG_LEAVE;
5949
  decrement_handler_count();
5950
  return 0;
5951 5952
}
#endif /* HAVE_SMEM */
5953
#endif /* EMBEDDED_LIBRARY */
unknown's avatar
unknown committed
5954

5955 5956 5957

/****************************************************************************
  Handle start options
unknown's avatar
unknown committed
5958 5959
******************************************************************************/

5960
DYNAMIC_ARRAY all_options;
5961

5962 5963 5964 5965 5966
/**
  System variables are automatically command-line options (few
  exceptions are documented in sys_var.h), so don't need
  to be listed here.
*/
5967

Marc Alff's avatar
Marc Alff committed
5968
struct my_option my_long_options[]=
5969
{
unknown's avatar
unknown committed
5970
  {"help", '?', "Display this help and exit.", 
5971
   &opt_help, &opt_help, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
unknown's avatar
unknown committed
5972 5973
   0, 0},
#ifdef HAVE_REPLICATION
5974
  {"abort-slave-event-count", 0,
unknown's avatar
unknown committed
5975
   "Option used by mysql-test for debugging and testing of replication.",
5976
   &abort_slave_event_count,  &abort_slave_event_count,
unknown's avatar
unknown committed
5977 5978
   0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif /* HAVE_REPLICATION */
5979
  {"allow-suspicious-udfs", 0,
unknown's avatar
unknown committed
5980 5981
   "Allows use of UDFs consisting of only one symbol xxx() "
   "without corresponding xxx_init() or xxx_deinit(). That also means "
5982 5983
   "that one can load any function from any library, for example exit() "
   "from libc.so",
5984
   &opt_allow_suspicious_udfs, &opt_allow_suspicious_udfs,
5985
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
5986 5987
  {"ansi", 'a', "Use ANSI SQL syntax instead of MySQL syntax. This mode "
   "will also set transaction isolation level 'serializable'.", 0, 0, 0,
unknown's avatar
unknown committed
5988
   GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
5989
  {"bind-address", OPT_BIND_ADDRESS, "IP address to bind to.",
5990
   &my_bind_addr_str, &my_bind_addr_str, 0, GET_STR,
unknown's avatar
unknown committed
5991
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
5992
  {"binlog-do-db", OPT_BINLOG_DO_DB,
5993 5994
   "Tells the master it should log updates for the specified database, "
   "and exclude all others not explicitly mentioned.",
5995
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
5996
  {"binlog-ignore-db", OPT_BINLOG_IGNORE_DB,
Staale Smedseng's avatar
Staale Smedseng committed
5997
   "Tells the master that updates to the given database should not be logged to the binary log.",
5998
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
5999
  {"binlog-row-event-max-size", 0,
6000 6001 6002
   "The maximum size of a row-based binary log event in bytes. Rows will be "
   "grouped into events smaller than this size if possible. "
   "The value has to be a multiple of 256.",
6003 6004
   &opt_binlog_rows_event_max_size, &opt_binlog_rows_event_max_size,
   0, GET_ULONG, REQUIRED_ARG,
6005 6006 6007 6008
   /* def_value */ 1024, /* min_value */  256, /* max_value */ ULONG_MAX, 
   /* sub_size */     0, /* block_size */ 256, 
   /* app_type */ 0
  },
6009
#ifndef DISABLE_GRANT_OPTIONS
6010
  {"bootstrap", OPT_BOOTSTRAP, "Used by mysql installation scripts.", 0, 0, 0,
6011
   GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
6012
#endif
6013
  {"character-set-client-handshake", 0,
unknown's avatar
unknown committed
6014
   "Don't ignore client side character set value sent during handshake.",
6015 6016
   &opt_character_set_client_handshake,
   &opt_character_set_client_handshake,
6017
    0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
6018
  {"character-set-filesystem", 0,
unknown's avatar
unknown committed
6019
   "Set the filesystem character set.",
6020 6021
   &character_set_filesystem_name,
   &character_set_filesystem_name,
unknown's avatar
unknown committed
6022
   0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 },
unknown's avatar
unknown committed
6023
  {"character-set-server", 'C', "Set the default character set.",
6024
   &default_character_set_name, &default_character_set_name,
unknown's avatar
unknown committed
6025
   0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 },
unknown's avatar
unknown committed
6026
  {"chroot", 'r', "Chroot mysqld daemon during startup.",
6027
   &mysqld_chroot, &mysqld_chroot, 0, GET_STR, REQUIRED_ARG,
unknown's avatar
unknown committed
6028
   0, 0, 0, 0, 0, 0},
6029
  {"collation-server", 0, "Set the default collation.",
6030
   &default_collation_name, &default_collation_name,
unknown's avatar
unknown committed
6031
   0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 },
Staale Smedseng's avatar
Staale Smedseng committed
6032
  {"console", OPT_CONSOLE, "Write error output on screen; don't remove the console window on windows.",
6033
   &opt_console, &opt_console, 0, GET_BOOL, NO_ARG, 0, 0, 0,
6034
   0, 0, 0},
6035
  {"core-file", OPT_WANT_CORE, "Write core on errors.", 0, 0, 0, GET_NO_ARG,
6036
   NO_ARG, 0, 0, 0, 0, 0, 0},
6037 6038 6039
  /* default-storage-engine should have "MyISAM" as def_value. Instead
     of initializing it here it is done in init_common_variables() due
     to a compiler bug in Sun Studio compiler. */
6040
  {"default-storage-engine", 0, "The default storage engine for new tables",
6041
   &default_storage_engine, 0, 0, GET_STR, REQUIRED_ARG,
6042
   0, 0, 0, 0, 0, 0 },
6043
  {"default-time-zone", 0, "Set the default time zone.",
6044
   &default_tz_name, &default_tz_name,
6045
   0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 },
unknown's avatar
unknown committed
6046
#ifdef HAVE_OPENSSL
6047
  {"des-key-file", 0,
unknown's avatar
unknown committed
6048
   "Load keys for des_encrypt() and des_encrypt from given file.",
6049
   &des_key_file, &des_key_file, 0, GET_STR, REQUIRED_ARG,
unknown's avatar
unknown committed
6050 6051 6052
   0, 0, 0, 0, 0, 0},
#endif /* HAVE_OPENSSL */
#ifdef HAVE_REPLICATION
6053
  {"disconnect-slave-event-count", 0,
unknown's avatar
unknown committed
6054
   "Option used by mysql-test for debugging and testing of replication.",
6055 6056
   &disconnect_slave_event_count, &disconnect_slave_event_count,
   0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
6057
#endif /* HAVE_REPLICATION */
6058
#ifdef HAVE_STACK_TRACE_ON_SEGV
6059
  {"enable-pstack", 0, "Print a symbolic stack trace on failure.",
6060
   &opt_do_pstack, &opt_do_pstack, 0, GET_BOOL, NO_ARG, 0, 0,
6061
   0, 0, 0, 0},
6062
#endif /* HAVE_STACK_TRACE_ON_SEGV */
Staale Smedseng's avatar
Staale Smedseng committed
6063
  {"exit-info", 'T', "Used for debugging. Use at your own risk.", 0, 0, 0,
6064
   GET_LONG, OPT_ARG, 0, 0, 0, 0, 0, 0},
6065 6066 6067 6068 6069

  {"external-locking", 0, "Use system (external) locking (disabled by "
   "default).  With this option enabled you can run myisamchk to test "
   "(not repair) tables while the MySQL server is running. Disable with "
   "--skip-external-locking.", &opt_external_locking, &opt_external_locking,
unknown's avatar
unknown committed
6070
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6071 6072
  /* We must always support the next option to make scripts like mysqltest
     easier to do */
6073
  {"gdb", 0,
Staale Smedseng's avatar
Staale Smedseng committed
6074
   "Set up signals usable for debugging.",
6075
   &opt_debugging, &opt_debugging,
6076
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6077
#ifdef HAVE_LARGE_PAGE_OPTION
6078
  {"super-large-pages", 0, "Enable support for super large pages.",
6079
   &opt_super_large_pages, &opt_super_large_pages, 0,
6080
   GET_BOOL, OPT_ARG, 0, 0, 1, 0, 1, 0},
unknown's avatar
Merge  
unknown committed
6081
#endif
6082
  {"language", 'L',
6083 6084
   "Client error messages in given language. May be given as a full path. "
   "Deprecated. Use --lc-messages-dir instead.",
6085
   &lc_messages_dir_ptr, &lc_messages_dir_ptr, 0,
6086
   GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6087
  {"lc-messages", 0,
6088
   "Set the language used for the error messages.",
6089
   &lc_messages, &lc_messages, 0, GET_STR, REQUIRED_ARG,
6090
   0, 0, 0, 0, 0, 0 },
6091
  {"lc-time-names", 0,
6092
   "Set the language used for the month names and the days of the week.",
6093
   &lc_time_names_name, &lc_time_names_name,
6094
   0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0 },
6095
  {"log", 'l', "Log connections and queries to file (deprecated option, use "
6096 6097
   "--general-log/--general-log-file instead).", &opt_logname, &opt_logname,
   0, GET_STR_ALLOC, OPT_ARG, 0, 0, 0, 0, 0, 0},
6098
  {"log-bin", OPT_BIN_LOG,
unknown's avatar
Merge  
unknown committed
6099 6100 6101
   "Log update queries in binary format. Optional (but strongly recommended "
   "to avoid replication problems if server's hostname changes) argument "
   "should be the chosen location for the binary log files.",
6102
   &opt_bin_logname, &opt_bin_logname, 0, GET_STR_ALLOC,
unknown's avatar
unknown committed
6103
   OPT_ARG, 0, 0, 0, 0, 0, 0},
6104
  {"log-bin-index", 0,
6105
   "File that holds the names for last binary log files.",
6106
   &opt_binlog_index_name, &opt_binlog_index_name, 0, GET_STR,
6107
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6108
  {"log-isam", OPT_ISAM_LOG, "Log all MyISAM changes to file.",
6109
   &myisam_log_filename, &myisam_log_filename, 0, GET_STR,
6110
   OPT_ARG, 0, 0, 0, 0, 0, 0},
6111
  {"log-short-format", 0,
unknown's avatar
unknown committed
6112
   "Don't log extra information to update and slow-query logs.",
6113
   &opt_short_log_format, &opt_short_log_format,
unknown's avatar
unknown committed
6114
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6115
  {"log-slow-admin-statements", 0,
6116 6117
   "Log slow OPTIMIZE, ANALYZE, ALTER and other administrative statements to "
   "the slow log if it is open.", &opt_log_slow_admin_statements,
6118
   &opt_log_slow_admin_statements, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6119
 {"log-slow-slave-statements", 0,
6120
  "Log slow statements executed by slave thread to the slow log if it is open.",
6121
  &opt_log_slow_slave_statements, &opt_log_slow_slave_statements,
6122
  0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
Konstantin Osipov's avatar
Konstantin Osipov committed
6123 6124 6125 6126 6127
  {"log-slow-queries", OPT_SLOW_QUERY_LOG,
   "Log slow queries to a table or log file. Defaults logging to table "
   "mysql.slow_log or hostname-slow.log if --log-output=file is used. "
   "Must be enabled to activate other slow log options. "
   "Deprecated option, use --slow-query-log/--slow-query-log-file instead.",
6128
   &opt_slow_logname, &opt_slow_logname, 0, GET_STR_ALLOC, OPT_ARG,
unknown's avatar
unknown committed
6129
   0, 0, 0, 0, 0, 0},
6130
  {"log-tc", 0,
unknown's avatar
Merge  
unknown committed
6131
   "Path to transaction coordinator log (used for transactions that affect "
Staale Smedseng's avatar
Staale Smedseng committed
6132
   "more than one storage engine, when binary log is disabled).",
6133
   &opt_tc_log_file, &opt_tc_log_file, 0, GET_STR,
unknown's avatar
Merge  
unknown committed
6134
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6135
#ifdef HAVE_MMAP
6136
  {"log-tc-size", 0, "Size of transaction coordinator log.",
6137
   &opt_tc_log_size, &opt_tc_log_size, 0, GET_ULONG,
6138 6139
   REQUIRED_ARG, TC_LOG_MIN_SIZE, TC_LOG_MIN_SIZE, ULONG_MAX, 0,
   TC_LOG_PAGE_SIZE, 0},
6140
#endif
6141
  {"master-info-file", 0,
6142 6143 6144
   "The location and name of the file that remembers the master and where "
   "the I/O replication thread is in the master's binlogs.",
   &master_info_file, &master_info_file, 0, GET_STR,
unknown's avatar
unknown committed
6145
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6146
  {"master-retry-count", 0,
6147
   "The number of tries the slave will make to connect to the master before giving up.",
6148
   &master_retry_count, &master_retry_count, 0, GET_ULONG,
6149
   REQUIRED_ARG, 3600*24, 0, 0, 0, 0, 0},
unknown's avatar
SCRUM  
unknown committed
6150
#ifdef HAVE_REPLICATION
6151
  {"init-rpl-role", 0, "Set the replication role.",
6152
   &rpl_status, &rpl_status, &rpl_role_typelib,
6153 6154
   GET_ENUM, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"max-binlog-dump-events", 0,
6155
   "Option used by mysql-test for debugging and testing of replication.",
6156
   &max_binlog_dump_events, &max_binlog_dump_events, 0,
6157
   GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
SCRUM  
unknown committed
6158
#endif /* HAVE_REPLICATION */
6159
  {"memlock", 0, "Lock mysqld in memory.", &locked_in_memory,
6160
   &locked_in_memory, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6161
  {"one-thread", OPT_ONE_THREAD,
Staale Smedseng's avatar
Staale Smedseng committed
6162 6163
   "(Deprecated): Only use one thread (for debugging under Linux). Use "
   "thread-handling=no-threads instead.",
unknown's avatar
unknown committed
6164
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
6165
  {"old-style-user-limits", 0,
Staale Smedseng's avatar
Staale Smedseng committed
6166 6167
   "Enable old-style user limits (before 5.0.3, user resources were counted "
   "per each user+host vs. per account).",
6168
   &opt_old_style_user_limits, &opt_old_style_user_limits,
unknown's avatar
Merge  
unknown committed
6169
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6170
  {"port-open-timeout", 0,
6171
   "Maximum time in seconds to wait for the port to become free. "
6172 6173
   "(Default: No wait).", &mysqld_port_timeout, &mysqld_port_timeout, 0,
   GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6174
  {"replicate-do-db", OPT_REPLICATE_DO_DB,
6175 6176 6177 6178 6179 6180 6181
   "Tells the slave thread to restrict replication to the specified database. "
   "To specify more than one database, use the directive multiple times, "
   "once for each database. Note that this will only work if you do not use "
   "cross-database queries such as UPDATE some_db.some_table SET foo='bar' "
   "while having selected a different or no database. If you need cross "
   "database updates to work, make sure you have 3.23.28 or later, and use "
   "replicate-wild-do-table=db_name.%.",
6182 6183
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"replicate-do-table", OPT_REPLICATE_DO_TABLE,
6184 6185 6186 6187
   "Tells the slave thread to restrict replication to the specified table. "
   "To specify more than one table, use the directive multiple times, once "
   "for each table. This will work for cross-database updates, in contrast "
   "to replicate-do-db.", 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6188
  {"replicate-ignore-db", OPT_REPLICATE_IGNORE_DB,
6189 6190 6191 6192 6193 6194
   "Tells the slave thread to not replicate to the specified database. To "
   "specify more than one database to ignore, use the directive multiple "
   "times, once for each database. This option will not work if you use "
   "cross database updates. If you need cross database updates to work, "
   "make sure you have 3.23.28 or later, and use replicate-wild-ignore-"
   "table=db_name.%. ", 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6195
  {"replicate-ignore-table", OPT_REPLICATE_IGNORE_TABLE,
6196 6197 6198
   "Tells the slave thread to not replicate to the specified table. To specify "
   "more than one table to ignore, use the directive multiple times, once for "
   "each table. This will work for cross-database updates, in contrast to "
6199
   "replicate-ignore-db.", 0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6200
  {"replicate-rewrite-db", OPT_REPLICATE_REWRITE_DB,
6201 6202
   "Updates to a database with a different name than the original. Example: "
   "replicate-rewrite-db=master_db_name->slave_db_name.",
6203
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
6204
#ifdef HAVE_REPLICATION
6205
  {"replicate-same-server-id", 0,
6206 6207 6208 6209
   "In replication, if set to 1, do not skip events having our server id. "
   "Default value is 0 (to break infinite loops in circular replication). "
   "Can't be set to 1 if --log-slave-updates is used.",
   &replicate_same_server_id, &replicate_same_server_id,
6210
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
6211
#endif
unknown's avatar
unknown committed
6212
  {"replicate-wild-do-table", OPT_REPLICATE_WILD_DO_TABLE,
6213 6214 6215 6216 6217 6218
   "Tells the slave thread to restrict replication to the tables that match "
   "the specified wildcard pattern. To specify more than one table, use the "
   "directive multiple times, once for each table. This will work for cross-"
   "database updates. Example: replicate-wild-do-table=foo%.bar% will "
   "replicate only updates to tables in all databases that start with foo "
   "and whose table names start with bar.",
unknown's avatar
unknown committed
6219 6220
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"replicate-wild-ignore-table", OPT_REPLICATE_WILD_IGNORE_TABLE,
6221 6222 6223 6224 6225 6226
   "Tells the slave thread to not replicate to the tables that match the "
   "given wildcard pattern. To specify more than one table to ignore, use "
   "the directive multiple times, once for each table. This will work for "
   "cross-database updates. Example: replicate-wild-ignore-table=foo%.bar% "
   "will not do updates to tables in databases that start with foo and whose "
   "table names start with bar.",
unknown's avatar
unknown committed
6227
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6228 6229
  {"safe-mode", OPT_SAFE, "Skip some optimize stages (for testing).",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
6230
  {"safe-user-create", 0,
6231
   "Don't allow new user creation by the user who has no write privileges to the mysql.user table.",
6232
   &opt_safe_user_create, &opt_safe_user_create, 0, GET_BOOL,
6233
   NO_ARG, 0, 0, 0, 0, 0, 0},
6234 6235
#if !defined(DBUG_OFF) && defined(SAFEMALLOC)
  {"safemalloc", 0, "Enable the memory allocation checking.",
6236
   &sf_malloc_quick, &sf_malloc_quick, 0,
6237 6238
   GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
  {"safemalloc-mem-limit", 0, "Simulate memory shortage.",
6239
   &sf_malloc_mem_limit, &sf_malloc_mem_limit, 0, GET_UINT,
6240
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6241
#endif
6242
  {"show-slave-auth-info", 0,
Staale Smedseng's avatar
Staale Smedseng committed
6243
   "Show user and password in SHOW SLAVE HOSTS on this master.",
6244
   &opt_show_slave_auth_info, &opt_show_slave_auth_info, 0,
6245
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6246
#ifndef DISABLE_GRANT_OPTIONS
6247
  {"skip-grant-tables", 0,
Staale Smedseng's avatar
Staale Smedseng committed
6248
   "Start without grant tables. This gives all users FULL ACCESS to all tables.",
6249
   &opt_noacl, &opt_noacl, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
6250
   0},
6251
#endif
unknown's avatar
unknown committed
6252 6253
  {"skip-host-cache", OPT_SKIP_HOST_CACHE, "Don't cache host names.", 0, 0, 0,
   GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
Staale Smedseng's avatar
Staale Smedseng committed
6254
  {"skip-new", OPT_SKIP_NEW, "Don't use new, possibly wrong routines.",
6255
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
6256
  {"skip-slave-start", 0,
6257 6258
   "If set, slave is not autostarted.", &opt_skip_slave_start,
   &opt_skip_slave_start, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6259
  {"skip-stack-trace", OPT_SKIP_STACK_TRACE,
6260
   "Don't print a stack trace on failure.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0,
6261 6262
   0, 0, 0, 0},
  {"skip-thread-priority", OPT_SKIP_PRIOR,
Konstantin Osipov's avatar
Konstantin Osipov committed
6263 6264 6265
   "Don't give threads different priorities. This option is deprecated "
   "because it has no effect; the implied behavior is already the default.",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
6266
#ifdef HAVE_REPLICATION
6267
  {"sporadic-binlog-dump-fail", 0,
unknown's avatar
unknown committed
6268
   "Option used by mysql-test for debugging and testing of replication.",
6269 6270
   &opt_sporadic_binlog_dump_fail,
   &opt_sporadic_binlog_dump_fail, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
unknown's avatar
unknown committed
6271 6272
   0},
#endif /* HAVE_REPLICATION */
6273
#ifdef HAVE_OPENSSL
6274 6275
  {"ssl", 0,
   "Enable SSL for connection (automatically enabled with other flags).",
6276
   &opt_use_ssl, &opt_use_ssl, 0, GET_BOOL, OPT_ARG, 0, 0, 0,
6277
   0, 0, 0},
6278
#endif
unknown's avatar
unknown committed
6279
#ifdef __WIN__
6280
  {"standalone", 0,
unknown's avatar
unknown committed
6281 6282 6283 6284
  "Dummy option to start as a standalone program (NT).", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
  {"symbolic-links", 's', "Enable symbolic link support.",
6285
   &my_use_symdir, &my_use_symdir, 0, GET_BOOL, NO_ARG,
6286 6287 6288 6289 6290
   /*
     The system call realpath() produces warnings under valgrind and
     purify. These are not suppressed: instead we disable symlinks
     option if compiled with valgrind support.
   */
6291
   IF_PURIFY(0,1), 0, 0, 0, 0, 0},
6292
  {"sysdate-is-now", 0,
6293 6294 6295 6296
   "Non-default option to alias SYSDATE() to NOW() to make it safe-replicable. "
   "Since 5.0, SYSDATE() returns a `dynamic' value different for different "
   "invocations, even within the same statement.",
   &global_system_variables.sysdate_is_now,
unknown's avatar
unknown committed
6297
   0, 0, GET_BOOL, NO_ARG, 0, 0, 1, 0, 1, 0},
6298
  {"tc-heuristic-recover", 0,
6299
   "Decision to use in heuristic recover process. Possible values are COMMIT "
6300
   "or ROLLBACK.", &tc_heuristic_recover, &tc_heuristic_recover,
6301
   &tc_heuristic_recover_typelib, GET_ENUM, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6302 6303 6304 6305 6306
#if defined(ENABLED_DEBUG_SYNC)
  {"debug-sync-timeout", OPT_DEBUG_SYNC_TIMEOUT,
   "Enable the debug sync facility "
   "and optionally specify a default wait timeout in seconds. "
   "A zero value keeps the facility disabled.",
6307
   &opt_debug_sync_timeout, 0,
6308 6309
   0, GET_UINT, OPT_ARG, 0, 0, UINT_MAX, 0, 0, 0},
#endif /* defined(ENABLED_DEBUG_SYNC) */
6310
  {"temp-pool", 0,
6311
#if (ENABLE_TEMP_POOL)
6312 6313
   "Using this option will cause most temporary files created to use a small "
   "set of names, rather than a unique name for each new file.",
6314 6315 6316
#else
   "This option is ignored on this OS.",
#endif
6317
   &use_temp_pool, &use_temp_pool, 0, GET_BOOL, NO_ARG, 1,
unknown's avatar
unknown committed
6318
   0, 0, 0, 0, 0},
6319 6320
  {"transaction-isolation", 0,
   "Default transaction isolation level.",
6321 6322
   &global_system_variables.tx_isolation,
   &global_system_variables.tx_isolation, &tx_isolation_typelib,
6323
   GET_ENUM, REQUIRED_ARG, ISO_REPEATABLE_READ, 0, 0, 0, 0, 0},
6324
  {"user", 'u', "Run mysqld daemon as user.", 0, 0, 0, GET_STR, REQUIRED_ARG,
unknown's avatar
unknown committed
6325
   0, 0, 0, 0, 0, 0},
Staale Smedseng's avatar
Staale Smedseng committed
6326
  {"verbose", 'v', "Used with --help option for detailed help.",
6327
   &opt_verbose, &opt_verbose, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
6328
  {"version", 'V', "Output version information and exit.", 0, 0, 0, GET_NO_ARG,
6329
   NO_ARG, 0, 0, 0, 0, 0, 0},
6330
  {"plugin-load", 0,
6331
   "Optional semicolon-separated list of plugins to load, where each plugin is "
6332 6333
   "identified as name=library, where name is the plugin name and library "
   "is the plugin library in plugin_dir.",
6334
   &opt_plugin_load, &opt_plugin_load, 0,
unknown's avatar
unknown committed
6335
   GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
6336
  {"table_cache", 0, "Deprecated; use --table-open-cache instead.",
6337
   &table_cache_size, &table_cache_size, 0, GET_ULONG,
6338
   REQUIRED_ARG, TABLE_OPEN_CACHE_DEFAULT, 1, 512*1024L, 0, 1, 0},
6339
  {0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
6340
};
unknown's avatar
unknown committed
6341

6342

6343
static int show_queries(THD *thd, SHOW_VAR *var, char *buff)
6344
{
6345
  var->type= SHOW_LONGLONG;
6346 6347 6348 6349
  var->value= (char *)&thd->query_id;
  return 0;
}

6350

6351
static int show_net_compression(THD *thd, SHOW_VAR *var, char *buff)
6352
{
6353
  var->type= SHOW_MY_BOOL;
6354 6355 6356 6357
  var->value= (char *)&thd->net.compress;
  return 0;
}

6358
static int show_starttime(THD *thd, SHOW_VAR *var, char *buff)
6359
{
6360
  var->type= SHOW_LONG;
6361
  var->value= buff;
unknown's avatar
unknown committed
6362
  *((long *)buff)= (long) (thd->query_start() - server_start_time);
6363 6364 6365
  return 0;
}

6366
#ifdef ENABLED_PROFILING
6367 6368 6369 6370 6371 6372 6373
static int show_flushstatustime(THD *thd, SHOW_VAR *var, char *buff)
{
  var->type= SHOW_LONG;
  var->value= buff;
  *((long *)buff)= (long) (thd->query_start() - flush_status_time);
  return 0;
}
6374
#endif
6375

6376
#ifdef HAVE_REPLICATION
6377
static int show_rpl_status(THD *thd, SHOW_VAR *var, char *buff)
6378
{
6379
  var->type= SHOW_CHAR;
6380 6381 6382 6383
  var->value= const_cast<char*>(rpl_status_type[(int)rpl_status]);
  return 0;
}

6384
static int show_slave_running(THD *thd, SHOW_VAR *var, char *buff)
6385
{
6386
  var->type= SHOW_MY_BOOL;
Marc Alff's avatar
Marc Alff committed
6387
  mysql_mutex_lock(&LOCK_active_mi);
6388
  var->value= buff;
6389 6390
  *((my_bool *)buff)= (my_bool) (active_mi && 
                                 active_mi->slave_running == MYSQL_SLAVE_RUN_CONNECT &&
6391
                                 active_mi->rli.slave_running);
Marc Alff's avatar
Marc Alff committed
6392
  mysql_mutex_unlock(&LOCK_active_mi);
6393 6394 6395
  return 0;
}

6396
static int show_slave_retried_trans(THD *thd, SHOW_VAR *var, char *buff)
6397 6398 6399 6400 6401
{
  /*
    TODO: with multimaster, have one such counter per line in
    SHOW SLAVE STATUS, and have the sum over all lines here.
  */
Marc Alff's avatar
Marc Alff committed
6402
  mysql_mutex_lock(&LOCK_active_mi);
6403 6404
  if (active_mi)
  {
6405
    var->type= SHOW_LONG;
6406
    var->value= buff;
Marc Alff's avatar
Marc Alff committed
6407
    mysql_mutex_lock(&active_mi->rli.data_lock);
6408
    *((long *)buff)= (long)active_mi->rli.retried_trans;
Marc Alff's avatar
Marc Alff committed
6409
    mysql_mutex_unlock(&active_mi->rli.data_lock);
6410 6411
  }
  else
6412
    var->type= SHOW_UNDEF;
Marc Alff's avatar
Marc Alff committed
6413
  mysql_mutex_unlock(&LOCK_active_mi);
6414 6415
  return 0;
}
Andrei Elkin's avatar
Andrei Elkin committed
6416 6417 6418

static int show_slave_received_heartbeats(THD *thd, SHOW_VAR *var, char *buff)
{
Marc Alff's avatar
Marc Alff committed
6419
  mysql_mutex_lock(&LOCK_active_mi);
Andrei Elkin's avatar
Andrei Elkin committed
6420 6421 6422 6423
  if (active_mi)
  {
    var->type= SHOW_LONGLONG;
    var->value= buff;
Marc Alff's avatar
Marc Alff committed
6424
    mysql_mutex_lock(&active_mi->rli.data_lock);
Andrei Elkin's avatar
Andrei Elkin committed
6425
    *((longlong *)buff)= active_mi->received_heartbeats;
Marc Alff's avatar
Marc Alff committed
6426
    mysql_mutex_unlock(&active_mi->rli.data_lock);
Andrei Elkin's avatar
Andrei Elkin committed
6427 6428 6429
  }
  else
    var->type= SHOW_UNDEF;
Marc Alff's avatar
Marc Alff committed
6430
  mysql_mutex_unlock(&LOCK_active_mi);
Andrei Elkin's avatar
Andrei Elkin committed
6431 6432 6433 6434 6435
  return 0;
}

static int show_heartbeat_period(THD *thd, SHOW_VAR *var, char *buff)
{
Marc Alff's avatar
Marc Alff committed
6436
  mysql_mutex_lock(&LOCK_active_mi);
Andrei Elkin's avatar
Andrei Elkin committed
6437 6438 6439 6440 6441 6442 6443 6444
  if (active_mi)
  {
    var->type= SHOW_CHAR;
    var->value= buff;
    my_sprintf(buff, (buff, "%.3f",active_mi->heartbeat_period));
  }
  else
    var->type= SHOW_UNDEF;
Marc Alff's avatar
Marc Alff committed
6445
  mysql_mutex_unlock(&LOCK_active_mi);
Andrei Elkin's avatar
Andrei Elkin committed
6446 6447 6448 6449
  return 0;
}


6450 6451
#endif /* HAVE_REPLICATION */

6452
static int show_open_tables(THD *thd, SHOW_VAR *var, char *buff)
6453
{
6454
  var->type= SHOW_LONG;
6455 6456 6457 6458 6459
  var->value= buff;
  *((long *)buff)= (long)cached_open_tables();
  return 0;
}

unknown's avatar
unknown committed
6460 6461 6462 6463
static int show_prepared_stmt_count(THD *thd, SHOW_VAR *var, char *buff)
{
  var->type= SHOW_LONG;
  var->value= buff;
Marc Alff's avatar
Marc Alff committed
6464
  mysql_mutex_lock(&LOCK_prepared_stmt_count);
unknown's avatar
unknown committed
6465
  *((long *)buff)= (long)prepared_stmt_count;
Marc Alff's avatar
Marc Alff committed
6466
  mysql_mutex_unlock(&LOCK_prepared_stmt_count);
unknown's avatar
unknown committed
6467 6468 6469
  return 0;
}

6470
static int show_table_definitions(THD *thd, SHOW_VAR *var, char *buff)
6471
{
6472
  var->type= SHOW_LONG;
6473 6474 6475 6476 6477
  var->value= buff;
  *((long *)buff)= (long)cached_table_definitions();
  return 0;
}

Konstantin Osipov's avatar
Konstantin Osipov committed
6478
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
6479
/* Functions relying on CTX */
6480
static int show_ssl_ctx_sess_accept(THD *thd, SHOW_VAR *var, char *buff)
6481
{
6482
  var->type= SHOW_LONG;
6483 6484 6485 6486 6487 6488
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_accept(ssl_acceptor_fd->ssl_context));
  return 0;
}

6489
static int show_ssl_ctx_sess_accept_good(THD *thd, SHOW_VAR *var, char *buff)
6490
{
6491
  var->type= SHOW_LONG;
6492 6493 6494 6495 6496 6497
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_accept_good(ssl_acceptor_fd->ssl_context));
  return 0;
}

6498
static int show_ssl_ctx_sess_connect_good(THD *thd, SHOW_VAR *var, char *buff)
6499
{
6500
  var->type= SHOW_LONG;
6501 6502 6503 6504 6505 6506
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_connect_good(ssl_acceptor_fd->ssl_context));
  return 0;
}

6507
static int show_ssl_ctx_sess_accept_renegotiate(THD *thd, SHOW_VAR *var, char *buff)
6508
{
6509
  var->type= SHOW_LONG;
6510 6511 6512 6513 6514 6515
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_accept_renegotiate(ssl_acceptor_fd->ssl_context));
  return 0;
}

6516
static int show_ssl_ctx_sess_connect_renegotiate(THD *thd, SHOW_VAR *var, char *buff)
6517
{
6518
  var->type= SHOW_LONG;
6519 6520 6521 6522 6523 6524
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_connect_renegotiate(ssl_acceptor_fd->ssl_context));
  return 0;
}

6525
static int show_ssl_ctx_sess_cb_hits(THD *thd, SHOW_VAR *var, char *buff)
6526
{
6527
  var->type= SHOW_LONG;
6528 6529 6530 6531 6532 6533
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_cb_hits(ssl_acceptor_fd->ssl_context));
  return 0;
}

6534
static int show_ssl_ctx_sess_hits(THD *thd, SHOW_VAR *var, char *buff)
6535
{
6536
  var->type= SHOW_LONG;
6537 6538 6539 6540 6541 6542
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_hits(ssl_acceptor_fd->ssl_context));
  return 0;
}

6543
static int show_ssl_ctx_sess_cache_full(THD *thd, SHOW_VAR *var, char *buff)
6544
{
6545
  var->type= SHOW_LONG;
6546 6547 6548 6549 6550 6551
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_cache_full(ssl_acceptor_fd->ssl_context));
  return 0;
}

6552
static int show_ssl_ctx_sess_misses(THD *thd, SHOW_VAR *var, char *buff)
6553
{
6554
  var->type= SHOW_LONG;
6555 6556 6557 6558 6559 6560
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_misses(ssl_acceptor_fd->ssl_context));
  return 0;
}

6561
static int show_ssl_ctx_sess_timeouts(THD *thd, SHOW_VAR *var, char *buff)
6562
{
6563
  var->type= SHOW_LONG;
6564 6565 6566 6567 6568 6569
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_timeouts(ssl_acceptor_fd->ssl_context));
  return 0;
}

6570
static int show_ssl_ctx_sess_number(THD *thd, SHOW_VAR *var, char *buff)
6571
{
6572
  var->type= SHOW_LONG;
6573 6574 6575 6576 6577 6578
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_number(ssl_acceptor_fd->ssl_context));
  return 0;
}

6579
static int show_ssl_ctx_sess_connect(THD *thd, SHOW_VAR *var, char *buff)
6580
{
6581
  var->type= SHOW_LONG;
6582 6583 6584 6585 6586 6587
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_connect(ssl_acceptor_fd->ssl_context));
  return 0;
}

6588
static int show_ssl_ctx_sess_get_cache_size(THD *thd, SHOW_VAR *var, char *buff)
6589
{
6590
  var->type= SHOW_LONG;
6591 6592 6593 6594 6595 6596
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_sess_get_cache_size(ssl_acceptor_fd->ssl_context));
  return 0;
}

6597
static int show_ssl_ctx_get_verify_mode(THD *thd, SHOW_VAR *var, char *buff)
6598
{
6599
  var->type= SHOW_LONG;
6600 6601 6602 6603 6604 6605
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_get_verify_mode(ssl_acceptor_fd->ssl_context));
  return 0;
}

6606
static int show_ssl_ctx_get_verify_depth(THD *thd, SHOW_VAR *var, char *buff)
6607
{
6608
  var->type= SHOW_LONG;
6609 6610 6611 6612 6613 6614
  var->value= buff;
  *((long *)buff)= (!ssl_acceptor_fd ? 0 :
                     SSL_CTX_get_verify_depth(ssl_acceptor_fd->ssl_context));
  return 0;
}

6615
static int show_ssl_ctx_get_session_cache_mode(THD *thd, SHOW_VAR *var, char *buff)
6616
{
6617
  var->type= SHOW_CHAR;
6618
  if (!ssl_acceptor_fd)
unknown's avatar
unknown committed
6619
    var->value= const_cast<char*>("NONE");
6620 6621 6622 6623
  else
    switch (SSL_CTX_get_session_cache_mode(ssl_acceptor_fd->ssl_context))
    {
    case SSL_SESS_CACHE_OFF:
unknown's avatar
unknown committed
6624
      var->value= const_cast<char*>("OFF"); break;
6625
    case SSL_SESS_CACHE_CLIENT:
unknown's avatar
unknown committed
6626
      var->value= const_cast<char*>("CLIENT"); break;
6627
    case SSL_SESS_CACHE_SERVER:
unknown's avatar
unknown committed
6628
      var->value= const_cast<char*>("SERVER"); break;
6629
    case SSL_SESS_CACHE_BOTH:
unknown's avatar
unknown committed
6630
      var->value= const_cast<char*>("BOTH"); break;
6631
    case SSL_SESS_CACHE_NO_AUTO_CLEAR:
unknown's avatar
unknown committed
6632
      var->value= const_cast<char*>("NO_AUTO_CLEAR"); break;
6633
    case SSL_SESS_CACHE_NO_INTERNAL_LOOKUP:
unknown's avatar
unknown committed
6634
      var->value= const_cast<char*>("NO_INTERNAL_LOOKUP"); break;
6635
    default:
unknown's avatar
unknown committed
6636
      var->value= const_cast<char*>("Unknown"); break;
6637 6638 6639 6640
    }
  return 0;
}

6641 6642 6643 6644 6645 6646 6647
/*
   Functions relying on SSL 
   Note: In the show_ssl_* functions, we need to check if we have a
         valid vio-object since this isn't always true, specifically
         when session_status or global_status is requested from
         inside an Event.
 */
6648
static int show_ssl_get_version(THD *thd, SHOW_VAR *var, char *buff)
6649
{
6650
  var->type= SHOW_CHAR;
6651 6652 6653
  if( thd->vio_ok() && thd->net.vio->ssl_arg )
    var->value= const_cast<char*>(SSL_get_version((SSL*) thd->net.vio->ssl_arg));
  else
6654
    var->value= (char *)"";
6655 6656 6657
  return 0;
}

6658
static int show_ssl_session_reused(THD *thd, SHOW_VAR *var, char *buff)
6659
{
6660
  var->type= SHOW_LONG;
6661
  var->value= buff;
6662 6663 6664 6665
  if( thd->vio_ok() && thd->net.vio->ssl_arg )
    *((long *)buff)= (long)SSL_session_reused((SSL*) thd->net.vio->ssl_arg);
  else
    *((long *)buff)= 0;
unknown's avatar
unknown committed
6666
  return 0;
6667 6668
}

6669
static int show_ssl_get_default_timeout(THD *thd, SHOW_VAR *var, char *buff)
6670
{
6671
  var->type= SHOW_LONG;
6672
  var->value= buff;
6673 6674 6675 6676
  if( thd->vio_ok() && thd->net.vio->ssl_arg )
    *((long *)buff)= (long)SSL_get_default_timeout((SSL*)thd->net.vio->ssl_arg);
  else
    *((long *)buff)= 0;
6677 6678 6679
  return 0;
}

6680
static int show_ssl_get_verify_mode(THD *thd, SHOW_VAR *var, char *buff)
6681
{
6682
  var->type= SHOW_LONG;
6683
  var->value= buff;
6684 6685 6686 6687
  if( thd->net.vio && thd->net.vio->ssl_arg )
    *((long *)buff)= (long)SSL_get_verify_mode((SSL*)thd->net.vio->ssl_arg);
  else
    *((long *)buff)= 0;
6688 6689 6690
  return 0;
}

6691
static int show_ssl_get_verify_depth(THD *thd, SHOW_VAR *var, char *buff)
6692
{
6693
  var->type= SHOW_LONG;
6694
  var->value= buff;
6695 6696 6697 6698
  if( thd->vio_ok() && thd->net.vio->ssl_arg )
    *((long *)buff)= (long)SSL_get_verify_depth((SSL*)thd->net.vio->ssl_arg);
  else
    *((long *)buff)= 0;
6699 6700 6701
  return 0;
}

6702
static int show_ssl_get_cipher(THD *thd, SHOW_VAR *var, char *buff)
6703
{
6704
  var->type= SHOW_CHAR;
6705 6706 6707
  if( thd->vio_ok() && thd->net.vio->ssl_arg )
    var->value= const_cast<char*>(SSL_get_cipher((SSL*) thd->net.vio->ssl_arg));
  else
6708
    var->value= (char *)"";
6709 6710 6711
  return 0;
}

6712
static int show_ssl_get_cipher_list(THD *thd, SHOW_VAR *var, char *buff)
6713
{
6714
  var->type= SHOW_CHAR;
6715
  var->value= buff;
6716
  if (thd->vio_ok() && thd->net.vio->ssl_arg)
6717 6718 6719
  {
    int i;
    const char *p;
6720 6721 6722
    char *end= buff + SHOW_VAR_FUNC_BUFF_SIZE;
    for (i=0; (p= SSL_get_cipher_list((SSL*) thd->net.vio->ssl_arg,i)) &&
               buff < end; i++)
6723
    {
6724
      buff= strnmov(buff, p, end-buff-1);
6725 6726 6727 6728 6729 6730 6731 6732 6733
      *buff++= ':';
    }
    if (i)
      buff--;
  }
  *buff=0;
  return 0;
}

Konstantin Osipov's avatar
Konstantin Osipov committed
6734
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
6735

6736

6737 6738 6739 6740
/*
  Variables shown by SHOW STATUS in alphabetical order
*/

6741
SHOW_VAR status_vars[]= {
6742 6743
  {"Aborted_clients",          (char*) &aborted_threads,        SHOW_LONG},
  {"Aborted_connects",         (char*) &aborted_connects,       SHOW_LONG},
6744 6745
  {"Binlog_cache_disk_use",    (char*) &binlog_cache_disk_use,  SHOW_LONG},
  {"Binlog_cache_use",         (char*) &binlog_cache_use,       SHOW_LONG},
6746 6747
  {"Bytes_received",           (char*) offsetof(STATUS_VAR, bytes_received), SHOW_LONGLONG_STATUS},
  {"Bytes_sent",               (char*) offsetof(STATUS_VAR, bytes_sent), SHOW_LONGLONG_STATUS},
unknown's avatar
unknown committed
6748
  {"Com",                      (char*) com_status_vars, SHOW_ARRAY},
6749
  {"Compression",              (char*) &show_net_compression, SHOW_FUNC},
6750
  {"Connections",              (char*) &thread_id,              SHOW_LONG_NOFLUSH},
unknown's avatar
Merge  
unknown committed
6751
  {"Created_tmp_disk_tables",  (char*) offsetof(STATUS_VAR, created_tmp_disk_tables), SHOW_LONG_STATUS},
6752
  {"Created_tmp_files",	       (char*) &my_tmp_file_created,	SHOW_LONG},
unknown's avatar
Merge  
unknown committed
6753
  {"Created_tmp_tables",       (char*) offsetof(STATUS_VAR, created_tmp_tables), SHOW_LONG_STATUS},
6754
  {"Delayed_errors",           (char*) &delayed_insert_errors,  SHOW_LONG},
6755
  {"Delayed_insert_threads",   (char*) &delayed_insert_threads, SHOW_LONG_NOFLUSH},
6756
  {"Delayed_writes",           (char*) &delayed_insert_writes,  SHOW_LONG},
6757
  {"Flush_commands",           (char*) &refresh_version,        SHOW_LONG_NOFLUSH},
unknown's avatar
Merge  
unknown committed
6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772
  {"Handler_commit",           (char*) offsetof(STATUS_VAR, ha_commit_count), SHOW_LONG_STATUS},
  {"Handler_delete",           (char*) offsetof(STATUS_VAR, ha_delete_count), SHOW_LONG_STATUS},
  {"Handler_discover",         (char*) offsetof(STATUS_VAR, ha_discover_count), SHOW_LONG_STATUS},
  {"Handler_prepare",          (char*) offsetof(STATUS_VAR, ha_prepare_count),  SHOW_LONG_STATUS},
  {"Handler_read_first",       (char*) offsetof(STATUS_VAR, ha_read_first_count), SHOW_LONG_STATUS},
  {"Handler_read_key",         (char*) offsetof(STATUS_VAR, ha_read_key_count), SHOW_LONG_STATUS},
  {"Handler_read_next",        (char*) offsetof(STATUS_VAR, ha_read_next_count), SHOW_LONG_STATUS},
  {"Handler_read_prev",        (char*) offsetof(STATUS_VAR, ha_read_prev_count), SHOW_LONG_STATUS},
  {"Handler_read_rnd",         (char*) offsetof(STATUS_VAR, ha_read_rnd_count), SHOW_LONG_STATUS},
  {"Handler_read_rnd_next",    (char*) offsetof(STATUS_VAR, ha_read_rnd_next_count), SHOW_LONG_STATUS},
  {"Handler_rollback",         (char*) offsetof(STATUS_VAR, ha_rollback_count), SHOW_LONG_STATUS},
  {"Handler_savepoint",        (char*) offsetof(STATUS_VAR, ha_savepoint_count), SHOW_LONG_STATUS},
  {"Handler_savepoint_rollback",(char*) offsetof(STATUS_VAR, ha_savepoint_rollback_count), SHOW_LONG_STATUS},
  {"Handler_update",           (char*) offsetof(STATUS_VAR, ha_update_count), SHOW_LONG_STATUS},
  {"Handler_write",            (char*) offsetof(STATUS_VAR, ha_write_count), SHOW_LONG_STATUS},
6773
  {"Key_blocks_not_flushed",   (char*) offsetof(KEY_CACHE, global_blocks_changed), SHOW_KEY_CACHE_LONG},
6774 6775
  {"Key_blocks_unused",        (char*) offsetof(KEY_CACHE, blocks_unused), SHOW_KEY_CACHE_LONG},
  {"Key_blocks_used",          (char*) offsetof(KEY_CACHE, blocks_used), SHOW_KEY_CACHE_LONG},
6776 6777 6778 6779
  {"Key_read_requests",        (char*) offsetof(KEY_CACHE, global_cache_r_requests), SHOW_KEY_CACHE_LONGLONG},
  {"Key_reads",                (char*) offsetof(KEY_CACHE, global_cache_read), SHOW_KEY_CACHE_LONGLONG},
  {"Key_write_requests",       (char*) offsetof(KEY_CACHE, global_cache_w_requests), SHOW_KEY_CACHE_LONGLONG},
  {"Key_writes",               (char*) offsetof(KEY_CACHE, global_cache_write), SHOW_KEY_CACHE_LONGLONG},
6780
  {"Last_query_cost",          (char*) offsetof(STATUS_VAR, last_query_cost), SHOW_DOUBLE_STATUS},
6781
  {"Max_used_connections",     (char*) &max_used_connections,  SHOW_LONG},
6782 6783 6784
  {"Not_flushed_delayed_rows", (char*) &delayed_rows_in_use,    SHOW_LONG_NOFLUSH},
  {"Open_files",               (char*) &my_file_opened,         SHOW_LONG_NOFLUSH},
  {"Open_streams",             (char*) &my_stream_opened,       SHOW_LONG_NOFLUSH},
6785 6786
  {"Open_table_definitions",   (char*) &show_table_definitions, SHOW_FUNC},
  {"Open_tables",              (char*) &show_open_tables,       SHOW_FUNC},
6787
  {"Opened_files",             (char*) &my_file_total_opened, SHOW_LONG_NOFLUSH},
unknown's avatar
Merge  
unknown committed
6788
  {"Opened_tables",            (char*) offsetof(STATUS_VAR, opened_tables), SHOW_LONG_STATUS},
6789
  {"Opened_table_definitions", (char*) offsetof(STATUS_VAR, opened_shares), SHOW_LONG_STATUS},
unknown's avatar
unknown committed
6790
  {"Prepared_stmt_count",      (char*) &show_prepared_stmt_count, SHOW_FUNC},
unknown's avatar
unknown committed
6791
#ifdef HAVE_QUERY_CACHE
6792 6793
  {"Qcache_free_blocks",       (char*) &query_cache.free_memory_blocks, SHOW_LONG_NOFLUSH},
  {"Qcache_free_memory",       (char*) &query_cache.free_memory, SHOW_LONG_NOFLUSH},
unknown's avatar
unknown committed
6794
  {"Qcache_hits",              (char*) &query_cache.hits,       SHOW_LONG},
6795
  {"Qcache_inserts",           (char*) &query_cache.inserts,    SHOW_LONG},
6796
  {"Qcache_lowmem_prunes",     (char*) &query_cache.lowmem_prunes, SHOW_LONG},
unknown's avatar
unknown committed
6797
  {"Qcache_not_cached",        (char*) &query_cache.refused,    SHOW_LONG},
6798 6799
  {"Qcache_queries_in_cache",  (char*) &query_cache.queries_in_cache, SHOW_LONG_NOFLUSH},
  {"Qcache_total_blocks",      (char*) &query_cache.total_blocks, SHOW_LONG_NOFLUSH},
unknown's avatar
unknown committed
6800
#endif /*HAVE_QUERY_CACHE*/
6801
  {"Queries",                  (char*) &show_queries,            SHOW_FUNC},
6802
  {"Questions",                (char*) offsetof(STATUS_VAR, questions), SHOW_LONG_STATUS},
6803 6804 6805
#ifdef HAVE_REPLICATION
  {"Rpl_status",               (char*) &show_rpl_status,          SHOW_FUNC},
#endif
unknown's avatar
Merge  
unknown committed
6806 6807 6808 6809 6810
  {"Select_full_join",         (char*) offsetof(STATUS_VAR, select_full_join_count), SHOW_LONG_STATUS},
  {"Select_full_range_join",   (char*) offsetof(STATUS_VAR, select_full_range_join_count), SHOW_LONG_STATUS},
  {"Select_range",             (char*) offsetof(STATUS_VAR, select_range_count), SHOW_LONG_STATUS},
  {"Select_range_check",       (char*) offsetof(STATUS_VAR, select_range_check_count), SHOW_LONG_STATUS},
  {"Select_scan",	       (char*) offsetof(STATUS_VAR, select_scan_count), SHOW_LONG_STATUS},
6811
  {"Slave_open_temp_tables",   (char*) &slave_open_temp_tables, SHOW_LONG},
6812 6813
#ifdef HAVE_REPLICATION
  {"Slave_retried_transactions",(char*) &show_slave_retried_trans, SHOW_FUNC},
Andrei Elkin's avatar
Andrei Elkin committed
6814 6815
  {"Slave_heartbeat_period",   (char*) &show_heartbeat_period, SHOW_FUNC},
  {"Slave_received_heartbeats",(char*) &show_slave_received_heartbeats, SHOW_FUNC},
6816 6817
  {"Slave_running",            (char*) &show_slave_running,     SHOW_FUNC},
#endif
6818
  {"Slow_launch_threads",      (char*) &slow_launch_threads,    SHOW_LONG},
unknown's avatar
Merge  
unknown committed
6819 6820 6821 6822 6823
  {"Slow_queries",             (char*) offsetof(STATUS_VAR, long_query_count), SHOW_LONG_STATUS},
  {"Sort_merge_passes",	       (char*) offsetof(STATUS_VAR, filesort_merge_passes), SHOW_LONG_STATUS},
  {"Sort_range",	       (char*) offsetof(STATUS_VAR, filesort_range_count), SHOW_LONG_STATUS},
  {"Sort_rows",		       (char*) offsetof(STATUS_VAR, filesort_rows), SHOW_LONG_STATUS},
  {"Sort_scan",		       (char*) offsetof(STATUS_VAR, filesort_scan_count), SHOW_LONG_STATUS},
unknown's avatar
unknown committed
6824
#ifdef HAVE_OPENSSL
Konstantin Osipov's avatar
Konstantin Osipov committed
6825
#ifndef EMBEDDED_LIBRARY
6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848
  {"Ssl_accept_renegotiates",  (char*) &show_ssl_ctx_sess_accept_renegotiate, SHOW_FUNC},
  {"Ssl_accepts",              (char*) &show_ssl_ctx_sess_accept, SHOW_FUNC},
  {"Ssl_callback_cache_hits",  (char*) &show_ssl_ctx_sess_cb_hits, SHOW_FUNC},
  {"Ssl_cipher",               (char*) &show_ssl_get_cipher, SHOW_FUNC},
  {"Ssl_cipher_list",          (char*) &show_ssl_get_cipher_list, SHOW_FUNC},
  {"Ssl_client_connects",      (char*) &show_ssl_ctx_sess_connect, SHOW_FUNC},
  {"Ssl_connect_renegotiates", (char*) &show_ssl_ctx_sess_connect_renegotiate, SHOW_FUNC},
  {"Ssl_ctx_verify_depth",     (char*) &show_ssl_ctx_get_verify_depth, SHOW_FUNC},
  {"Ssl_ctx_verify_mode",      (char*) &show_ssl_ctx_get_verify_mode, SHOW_FUNC},
  {"Ssl_default_timeout",      (char*) &show_ssl_get_default_timeout, SHOW_FUNC},
  {"Ssl_finished_accepts",     (char*) &show_ssl_ctx_sess_accept_good, SHOW_FUNC},
  {"Ssl_finished_connects",    (char*) &show_ssl_ctx_sess_connect_good, SHOW_FUNC},
  {"Ssl_session_cache_hits",   (char*) &show_ssl_ctx_sess_hits, SHOW_FUNC},
  {"Ssl_session_cache_misses", (char*) &show_ssl_ctx_sess_misses, SHOW_FUNC},
  {"Ssl_session_cache_mode",   (char*) &show_ssl_ctx_get_session_cache_mode, SHOW_FUNC},
  {"Ssl_session_cache_overflows", (char*) &show_ssl_ctx_sess_cache_full, SHOW_FUNC},
  {"Ssl_session_cache_size",   (char*) &show_ssl_ctx_sess_get_cache_size, SHOW_FUNC},
  {"Ssl_session_cache_timeouts", (char*) &show_ssl_ctx_sess_timeouts, SHOW_FUNC},
  {"Ssl_sessions_reused",      (char*) &show_ssl_session_reused, SHOW_FUNC},
  {"Ssl_used_session_cache_entries",(char*) &show_ssl_ctx_sess_number, SHOW_FUNC},
  {"Ssl_verify_depth",         (char*) &show_ssl_get_verify_depth, SHOW_FUNC},
  {"Ssl_verify_mode",          (char*) &show_ssl_get_verify_mode, SHOW_FUNC},
  {"Ssl_version",              (char*) &show_ssl_get_version, SHOW_FUNC},
Konstantin Osipov's avatar
Konstantin Osipov committed
6849
#endif
unknown's avatar
unknown committed
6850
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
6851 6852
  {"Table_locks_immediate",    (char*) &locks_immediate,        SHOW_LONG},
  {"Table_locks_waited",       (char*) &locks_waited,           SHOW_LONG},
6853
#ifdef HAVE_MMAP
unknown's avatar
Merge  
unknown committed
6854 6855 6856
  {"Tc_log_max_pages_used",    (char*) &tc_log_max_pages_used,  SHOW_LONG},
  {"Tc_log_page_size",         (char*) &tc_log_page_size,       SHOW_LONG},
  {"Tc_log_page_waits",        (char*) &tc_log_page_waits,      SHOW_LONG},
6857
#endif
6858
  {"Threads_cached",           (char*) &cached_thread_count,    SHOW_LONG_NOFLUSH},
Konstantin Osipov's avatar
Konstantin Osipov committed
6859
  {"Threads_connected",        (char*) &connection_count,       SHOW_INT},
6860 6861
  {"Threads_created",	       (char*) &thread_created,		SHOW_LONG_NOFLUSH},
  {"Threads_running",          (char*) &thread_running,         SHOW_INT},
6862
  {"Uptime",                   (char*) &show_starttime,         SHOW_FUNC},
6863
#ifdef ENABLED_PROFILING
6864
  {"Uptime_since_flush_status",(char*) &show_flushstatustime,   SHOW_FUNC},
6865
#endif
6866
  {NullS, NullS, SHOW_LONG}
unknown's avatar
unknown committed
6867 6868
};

Marc Alff's avatar
Marc Alff committed
6869
bool add_terminator(DYNAMIC_ARRAY *options)
6870 6871
{
  my_option empty_element= {0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0};
Marc Alff's avatar
Marc Alff committed
6872
  return insert_dynamic(options, (uchar *)&empty_element);
6873 6874
}

6875
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
6876 6877
static void print_version(void)
{
6878
  set_server_version();
6879

6880 6881
  printf("%s  Ver %s for %s on %s (%s)\n",my_progname,
	 server_version,SYSTEM_TYPE,MACHINE_TYPE, MYSQL_COMPILATION_COMMENT);
unknown's avatar
unknown committed
6882 6883
}

6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915
/** Compares two options' names, treats - and _ the same */
static int option_cmp(my_option *a, my_option *b)
{
  const char *sa= a->name;
  const char *sb= b->name;
  for (; *sa || *sb; sa++, sb++)
  {
    if (*sa < *sb)
    {
      if (*sa == '-' && *sb == '_')
        continue;
      else
        return -1;
    }
    if (*sa > *sb)
    {
      if (*sa == '_' && *sb == '-')
        continue;
      else
        return 1;
    }
  }
  DBUG_ASSERT(a->name == b->name);
  return 0;
}

static void print_help()
{
  MEM_ROOT mem_root;
  init_alloc_root(&mem_root, 4096, 4096);

  pop_dynamic(&all_options);
Marc Alff's avatar
Marc Alff committed
6916
  sys_var_add_options(&all_options, sys_var::PARSE_EARLY);
6917 6918
  add_plugin_options(&all_options, &mem_root);
  sort_dynamic(&all_options, (qsort_cmp) option_cmp);
Marc Alff's avatar
Marc Alff committed
6919
  add_terminator(&all_options);
6920 6921 6922 6923 6924 6925 6926 6927

  my_print_help((my_option*) all_options.buffer);
  my_print_variables((my_option*) all_options.buffer);

  free_root(&mem_root, MYF(0));
  delete_dynamic(&all_options);
}

unknown's avatar
unknown committed
6928 6929
static void usage(void)
{
6930
  DBUG_ENTER("usage");
6931
  if (!(default_charset_info= get_charset_by_csname(default_character_set_name,
unknown's avatar
unknown committed
6932 6933 6934 6935 6936
					           MY_CS_PRIMARY,
						   MYF(MY_WME))))
    exit(1);
  if (!default_collation_name)
    default_collation_name= (char*) default_charset_info->name;
unknown's avatar
unknown committed
6937
  print_version();
unknown's avatar
unknown committed
6938
  puts("\
Staale Smedseng's avatar
Staale Smedseng committed
6939
Copyright (C) 2000-2008 MySQL AB, by Monty and others.\n\
6940
Copyright (C) 2008,2009 Sun Microsystems, Inc.\n\
unknown's avatar
unknown committed
6941
This software comes with ABSOLUTELY NO WARRANTY. This is free software,\n\
6942
and you are welcome to modify and redistribute it under the GPL license\n\n\
Staale Smedseng's avatar
Staale Smedseng committed
6943
Starts the MySQL database server.\n");
unknown's avatar
unknown committed
6944 6945

  printf("Usage: %s [OPTIONS]\n", my_progname);
6946
  if (!opt_verbose)
Staale Smedseng's avatar
Staale Smedseng committed
6947
    puts("\nFor more help options (several pages), use mysqld --verbose --help.");
6948 6949
  else
  {
unknown's avatar
unknown committed
6950 6951
#ifdef __WIN__
  puts("NT and Win32 specific options:\n\
Staale Smedseng's avatar
Staale Smedseng committed
6952 6953 6954 6955 6956 6957 6958 6959
  --install                     Install the default service (NT).\n\
  --install-manual              Install the default service started manually (NT).\n\
  --install service_name        Install an optional service (NT).\n\
  --install-manual service_name Install an optional service started manually (NT).\n\
  --remove                      Remove the default service from the service list (NT).\n\
  --remove service_name         Remove the service_name from the service list (NT).\n\
  --enable-named-pipe           Only to be used for the default server (NT).\n\
  --standalone                  Dummy option to start as a standalone server (NT).\
unknown's avatar
unknown committed
6960
");
6961
  puts("");
unknown's avatar
unknown committed
6962
#endif
6963
  print_defaults(MYSQL_CONFIG_NAME,load_default_groups);
unknown's avatar
unknown committed
6964 6965
  puts("");
  set_ports();
6966

unknown's avatar
unknown committed
6967
  /* Print out all the options including plugin supplied options */
6968
  print_help();
6969

6970 6971 6972 6973 6974 6975 6976
  if (! plugins_are_initialized)
  {
    puts("\n\
Plugins have parameters that are not reflected in this list\n\
because execution stopped before plugins were initialized.");
  }

unknown's avatar
unknown committed
6977
  puts("\n\
unknown's avatar
unknown committed
6978
To see what values a running MySQL server is using, type\n\
6979
'mysqladmin variables' instead of 'mysqld --verbose --help'.");
6980
  }
6981
  DBUG_VOID_RETURN;
unknown's avatar
unknown committed
6982
}
6983
#endif /*!EMBEDDED_LIBRARY*/
unknown's avatar
unknown committed
6984

unknown's avatar
unknown committed
6985
/**
6986
  Initialize MySQL global variables to default values.
unknown's avatar
unknown committed
6987

unknown's avatar
unknown committed
6988
  @note
unknown's avatar
unknown committed
6989 6990 6991 6992
    The reason to set a lot of global variables to zero is to allow one to
    restart the embedded server with a clean environment
    It's also needed on some exotic platforms where global variables are
    not set to 0 when a program starts.
unknown's avatar
unknown committed
6993

6994
    We don't need to set variables refered to in my_long_options
unknown's avatar
unknown committed
6995 6996
    as these are initialized by my_getopt.
*/
unknown's avatar
unknown committed
6997

6998
static int mysql_init_variables(void)
unknown's avatar
unknown committed
6999 7000 7001 7002
{
  /* Things reset to zero */
  opt_skip_slave_start= opt_reckless_slave = 0;
  mysql_home[0]= pidfile_name[0]= log_error_file[0]= 0;
7003
  myisam_test_invalid_symlink= test_if_data_home_dir;
unknown's avatar
unknown committed
7004
  opt_log= opt_slow_log= 0;
7005
  opt_bin_log= 0;
unknown's avatar
unknown committed
7006
  opt_disable_networking= opt_skip_show_db=0;
7007
  opt_skip_name_resolve= 0;
7008
  opt_ignore_builtin_innodb= 0;
unknown's avatar
Merge  
unknown committed
7009 7010
  opt_logname= opt_update_logname= opt_binlog_index_name= opt_slow_logname= 0;
  opt_tc_log_file= (char *)"tc.log";      // no hostname in tc_log file name !
7011 7012
  opt_secure_auth= 0;
  opt_bootstrap= opt_myisam_log= 0;
unknown's avatar
unknown committed
7013 7014 7015 7016 7017 7018 7019 7020 7021
  mqh_used= 0;
  segfaulted= kill_in_progress= 0;
  cleanup_done= 0;
  server_id_supplied= 0;
  test_flags= select_errors= dropping_tables= ha_open_options=0;
  thread_count= thread_running= kill_cached_threads= wake_thread=0;
  slave_open_temp_tables= 0;
  cached_thread_count= 0;
  opt_endinfo= using_udf_functions= 0;
7022
  opt_using_transactions= 0;
unknown's avatar
unknown committed
7023 7024
  abort_loop= select_thread_in_use= signal_thread_in_use= 0;
  ready_to_exit= shutdown_in_progress= grant_option= 0;
unknown's avatar
Merge  
unknown committed
7025
  aborted_threads= aborted_connects= 0;
unknown's avatar
unknown committed
7026 7027
  delayed_insert_threads= delayed_insert_writes= delayed_rows_in_use= 0;
  delayed_insert_errors= thread_created= 0;
unknown's avatar
Merge  
unknown committed
7028
  specialflag= 0;
7029
  binlog_cache_use=  binlog_cache_disk_use= 0;
unknown's avatar
unknown committed
7030 7031
  max_used_connections= slow_launch_threads = 0;
  mysqld_user= mysqld_chroot= opt_init_file= opt_bin_logname = 0;
7032
  prepared_stmt_count= 0;
7033
  mysqld_unix_port= opt_mysql_tmpdir= my_bind_addr_str= NullS;
7034
  bzero((uchar*) &mysql_tmpdir_list, sizeof(mysql_tmpdir_list));
unknown's avatar
Merge  
unknown committed
7035
  bzero((char *) &global_status_var, sizeof(global_status_var));
7036
  opt_large_pages= 0;
7037
  opt_super_large_pages= 0;
7038 7039 7040
#if defined(ENABLED_DEBUG_SYNC)
  opt_debug_sync_timeout= 0;
#endif /* defined(ENABLED_DEBUG_SYNC) */
7041
  key_map_full.set_all();
unknown's avatar
unknown committed
7042

7043 7044 7045 7046 7047
  /* Character sets */
  system_charset_info= &my_charset_utf8_general_ci;
  files_charset_info= &my_charset_utf8_general_ci;
  national_charset_info= &my_charset_utf8_general_ci;
  table_alias_charset= &my_charset_bin;
unknown's avatar
unknown committed
7048
  character_set_filesystem= &my_charset_bin;
7049

unknown's avatar
unknown committed
7050 7051 7052 7053 7054
  opt_specialflag= SPECIAL_ENGLISH;
  unix_sock= ip_sock= INVALID_SOCKET;
  mysql_home_ptr= mysql_home;
  pidfile_name_ptr= pidfile_name;
  log_error_file_ptr= log_error_file;
7055
  lc_messages_dir_ptr= lc_messages_dir;
unknown's avatar
unknown committed
7056 7057
  protocol_version= PROTOCOL_VERSION;
  what_to_log= ~ (1L << (uint) COM_TIME);
7058
  refresh_version= 1L;	/* Increments on each reload */
7059
  global_query_id= thread_id= 1L;
7060
  my_atomic_rwlock_init(&global_query_id_lock);
7061
  my_atomic_rwlock_init(&thread_running_lock);
unknown's avatar
unknown committed
7062 7063 7064
  strmov(server_version, MYSQL_SERVER_VERSION);
  threads.empty();
  thread_cache.empty();
7065
  key_caches.empty();
unknown's avatar
unknown committed
7066
  if (!(dflt_key_cache= get_or_create_key_cache(default_key_cache_base.str,
7067
                                                default_key_cache_base.length)))
7068 7069 7070 7071
  {
    sql_print_error("Cannot allocate the keycache");
    return 1;
  }
7072 7073
  /* set key_cache_hash.default_value = dflt_key_cache */
  multi_keycache_init();
unknown's avatar
unknown committed
7074 7075

  /* Set directory paths */
7076 7077 7078
  mysql_real_data_home_len=
    strmake(mysql_real_data_home, get_relative_path(MYSQL_DATADIR),
            sizeof(mysql_real_data_home)-1) - mysql_real_data_home;
unknown's avatar
unknown committed
7079 7080
  /* Replication parameters */
  master_info_file= (char*) "master.info",
unknown's avatar
unknown committed
7081
    relay_log_info_file= (char*) "relay-log.info";
unknown's avatar
unknown committed
7082 7083 7084 7085 7086
  report_user= report_password = report_host= 0;	/* TO BE DELETED */
  opt_relay_logname= opt_relaylog_index_name= 0;

  /* Variables in libraries */
  charsets_dir= 0;
7087
  default_character_set_name= (char*) MYSQL_DEFAULT_CHARSET_NAME;
7088
  default_collation_name= compiled_default_collation_name;
unknown's avatar
unknown committed
7089
  character_set_filesystem_name= (char*) "binary";
7090
  lc_messages= (char*) "en_US";
7091
  lc_time_names_name= (char*) "en_US";
7092
  
unknown's avatar
unknown committed
7093 7094 7095 7096 7097 7098
  /* Variables that depends on compile options */
#ifndef DBUG_OFF
  default_dbug_option=IF_WIN("d:t:i:O,\\mysqld.trace",
			     "d:t:i:o,/tmp/mysqld.trace");
#endif
  opt_error_log= IF_WIN(1,0);
7099 7100
#ifdef ENABLED_PROFILING
    have_profiling = SHOW_OPTION_YES;
7101
#else
7102
    have_profiling = SHOW_OPTION_NO;
7103
#endif
7104

unknown's avatar
unknown committed
7105
#ifdef HAVE_OPENSSL
7106
  have_ssl=SHOW_OPTION_YES;
unknown's avatar
unknown committed
7107
#else
7108
  have_ssl=SHOW_OPTION_NO;
unknown's avatar
unknown committed
7109
#endif
unknown's avatar
unknown committed
7110
#ifdef HAVE_BROKEN_REALPATH
unknown's avatar
unknown committed
7111 7112 7113 7114
  have_symlink=SHOW_OPTION_NO;
#else
  have_symlink=SHOW_OPTION_YES;
#endif
7115 7116 7117 7118 7119
#ifdef HAVE_DLOPEN
  have_dlopen=SHOW_OPTION_YES;
#else
  have_dlopen=SHOW_OPTION_NO;
#endif
unknown's avatar
unknown committed
7120 7121 7122 7123 7124
#ifdef HAVE_QUERY_CACHE
  have_query_cache=SHOW_OPTION_YES;
#else
  have_query_cache=SHOW_OPTION_NO;
#endif
7125 7126 7127 7128 7129 7130 7131 7132 7133 7134
#ifdef HAVE_SPATIAL
  have_geometry=SHOW_OPTION_YES;
#else
  have_geometry=SHOW_OPTION_NO;
#endif
#ifdef HAVE_RTREE_KEYS
  have_rtree_keys=SHOW_OPTION_YES;
#else
  have_rtree_keys=SHOW_OPTION_NO;
#endif
unknown's avatar
unknown committed
7135 7136 7137 7138 7139 7140
#ifdef HAVE_CRYPT
  have_crypt=SHOW_OPTION_YES;
#else
  have_crypt=SHOW_OPTION_NO;
#endif
#ifdef HAVE_COMPRESS
7141
  have_compress= SHOW_OPTION_YES;
unknown's avatar
unknown committed
7142
#else
7143
  have_compress= SHOW_OPTION_NO;
unknown's avatar
unknown committed
7144 7145 7146 7147 7148 7149
#endif
#ifdef HAVE_LIBWRAP
  libwrapName= NullS;
#endif
#ifdef HAVE_OPENSSL
  des_key_file = 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
7150
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
7151
  ssl_acceptor_fd= 0;
Konstantin Osipov's avatar
Konstantin Osipov committed
7152 7153
#endif /* ! EMBEDDED_LIBRARY */
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
7154 7155 7156 7157
#ifdef HAVE_SMEM
  shared_memory_base_name= default_shared_memory_base_name;
#endif

unknown's avatar
unknown committed
7158 7159
#if defined(__WIN__) || defined(__NETWARE__)
  /* Allow Win32 and NetWare users to move MySQL anywhere */
unknown's avatar
unknown committed
7160 7161
  {
    char prg_dev[LIBLEN];
7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173
#if defined __WIN__
	char executing_path_name[LIBLEN];
	if (!test_if_hard_path(my_progname))
	{
		// we don't want to use GetModuleFileName inside of my_path since
		// my_path is a generic path dereferencing function and here we care
		// only about the executing binary.
		GetModuleFileName(NULL, executing_path_name, sizeof(executing_path_name));
		my_path(prg_dev, executing_path_name, NULL);
	}
	else
#endif
unknown's avatar
unknown committed
7174 7175 7176 7177 7178 7179
    my_path(prg_dev,my_progname,"mysql/bin");
    strcat(prg_dev,"/../");			// Remove 'bin' to get base dir
    cleanup_dirname(mysql_home,prg_dev);
  }
#else
  const char *tmpenv;
unknown's avatar
unknown committed
7180
  if (!(tmpenv = getenv("MY_BASEDIR_VERSION")))
unknown's avatar
unknown committed
7181
    tmpenv = DEFAULT_MYSQL_HOME;
unknown's avatar
unknown committed
7182
  (void) strmake(mysql_home, tmpenv, sizeof(mysql_home)-1);
unknown's avatar
unknown committed
7183
#endif
7184
  return 0;
unknown's avatar
unknown committed
7185 7186
}

7187 7188 7189 7190
my_bool
mysqld_get_one_option(int optid,
                      const struct my_option *opt __attribute__((unused)),
                      char *argument)
unknown's avatar
unknown committed
7191
{
7192 7193
  switch(optid) {
  case '#':
7194
#ifndef DBUG_OFF
unknown's avatar
unknown committed
7195
    DBUG_SET_INITIAL(argument ? argument : default_dbug_option);
7196 7197 7198 7199
#endif
    opt_endinfo=1;				/* unireg: memory allocation */
    break;
  case 'a':
7200
    global_system_variables.sql_mode= MODE_ANSI;
unknown's avatar
unknown committed
7201
    global_system_variables.tx_isolation= ISO_SERIALIZABLE;
7202 7203 7204 7205
    break;
  case 'b':
    strmake(mysql_home,argument,sizeof(mysql_home)-1);
    break;
7206
  case 'C':
7207 7208
    if (default_collation_name == compiled_default_collation_name)
      default_collation_name= 0;
7209
    break;
7210
  case 'l':
7211
    WARN_DEPRECATED(NULL, 7, 0, "--log", "'--general-log'/'--general-log-file'");
7212 7213 7214 7215
    opt_log=1;
    break;
  case 'h':
    strmake(mysql_real_data_home,argument, sizeof(mysql_real_data_home)-1);
7216
    /* Correct pointer set by my_getopt (for embedded library) */
7217
    mysql_real_data_home_ptr= mysql_real_data_home;
7218
    break;
7219
  case 'u':
7220
    if (!mysqld_user || !strcmp(mysqld_user, argument))
unknown's avatar
unknown committed
7221
      mysqld_user= argument;
7222
    else
7223
      sql_print_warning("Ignoring user change to '%s' because the user was set to '%s' earlier on the command line\n", argument, mysqld_user);
7224
    break;
7225
  case 'L':
7226
    strmake(lc_messages_dir, argument, sizeof(lc_messages_dir)-1);
7227
    lc_messages_dir_ptr= lc_messages_dir;
7228
    break;
7229 7230
  case OPT_BINLOG_FORMAT:
    binlog_format_used= true;
7231
    break;
7232
#include <sslopt-case.h>
7233
#ifndef EMBEDDED_LIBRARY
7234 7235 7236
  case 'V':
    print_version();
    exit(0);
7237
#endif /*EMBEDDED_LIBRARY*/
7238 7239 7240 7241 7242 7243 7244 7245
  case 'W':
    if (!argument)
      global_system_variables.log_warnings++;
    else if (argument == disabled_my_option)
      global_system_variables.log_warnings= 0L;
    else
      global_system_variables.log_warnings= atoi(argument);
    break;
7246 7247 7248 7249 7250 7251 7252 7253
  case 'T':
    test_flags= argument ? (uint) atoi(argument) : 0;
    opt_endinfo=1;
    break;
  case (int) OPT_ISAM_LOG:
    opt_myisam_log=1;
    break;
  case (int) OPT_BIN_LOG:
7254
    opt_bin_log= test(argument != disabled_my_option);
7255
    break;
unknown's avatar
SCRUM  
unknown committed
7256
#ifdef HAVE_REPLICATION
7257
  case (int)OPT_REPLICATE_IGNORE_DB:
7258
  {
7259
    rpl_filter->add_ignore_db(argument);
7260 7261 7262 7263
    break;
  }
  case (int)OPT_REPLICATE_DO_DB:
  {
7264
    rpl_filter->add_do_db(argument);
7265 7266 7267 7268 7269
    break;
  }
  case (int)OPT_REPLICATE_REWRITE_DB:
  {
    char* key = argument,*p, *val;
7270

7271
    if (!(p= strstr(argument, "->")))
7272
    {
7273 7274
      sql_print_error("Bad syntax in replicate-rewrite-db - missing '->'!\n");
      return 1;
7275
    }
7276
    val= p--;
unknown's avatar
unknown committed
7277
    while (my_isspace(mysqld_charset, *p) && p > argument)
7278 7279
      *p-- = 0;
    if (p == argument)
7280
    {
7281 7282
      sql_print_error("Bad syntax in replicate-rewrite-db - empty FROM db!\n");
      return 1;
7283
    }
7284 7285
    *val= 0;
    val+= 2;
unknown's avatar
unknown committed
7286
    while (*val && my_isspace(mysqld_charset, *val))
7287 7288
      *val++;
    if (!*val)
7289
    {
7290 7291
      sql_print_error("Bad syntax in replicate-rewrite-db - empty TO db!\n");
      return 1;
7292 7293
    }

7294
    rpl_filter->add_db_rewrite(key, val);
7295 7296 7297
    break;
  }

7298
  case (int)OPT_BINLOG_IGNORE_DB:
7299
  {
7300
    binlog_filter->add_ignore_db(argument);
7301 7302
    break;
  }
7303
  case (int)OPT_BINLOG_DO_DB:
7304
  {
7305
    binlog_filter->add_do_db(argument);
7306 7307
    break;
  }
7308
  case (int)OPT_REPLICATE_DO_TABLE:
7309
  {
7310
    if (rpl_filter->add_do_table(argument))
7311
    {
7312 7313
      sql_print_error("Could not add do table rule '%s'!\n", argument);
      return 1;
7314
    }
7315 7316
    break;
  }
7317
  case (int)OPT_REPLICATE_WILD_DO_TABLE:
7318
  {
7319
    if (rpl_filter->add_wild_do_table(argument))
7320
    {
7321 7322
      sql_print_error("Could not add do table rule '%s'!\n", argument);
      return 1;
7323
    }
7324 7325
    break;
  }
7326
  case (int)OPT_REPLICATE_WILD_IGNORE_TABLE:
7327
  {
7328
    if (rpl_filter->add_wild_ignore_table(argument))
7329
    {
7330 7331
      sql_print_error("Could not add ignore table rule '%s'!\n", argument);
      return 1;
7332
    }
7333 7334
    break;
  }
7335
  case (int)OPT_REPLICATE_IGNORE_TABLE:
7336
  {
7337
    if (rpl_filter->add_ignore_table(argument))
7338
    {
7339 7340
      sql_print_error("Could not add ignore table rule '%s'!\n", argument);
      return 1;
7341
    }
7342 7343
    break;
  }
unknown's avatar
SCRUM  
unknown committed
7344
#endif /* HAVE_REPLICATION */
7345
  case (int) OPT_SLOW_QUERY_LOG:
7346
    WARN_DEPRECATED(NULL, 7, 0, "--log-slow-queries", "'--slow-query-log'/'--slow-query-log-file'");
7347
    opt_slow_log= 1;
7348
    break;
7349 7350
  case (int) OPT_SKIP_NEW:
    opt_specialflag|= SPECIAL_NO_NEW_FUNC;
7351
    delay_key_write_options= DELAY_KEY_WRITE_NONE;
7352
    myisam_concurrent_insert=0;
7353
    myisam_recover_options= HA_RECOVER_OFF;
unknown's avatar
Merge  
unknown committed
7354
    sp_automatic_privileges=0;
7355
    my_use_symdir=0;
7356
    ha_open_options&= ~(HA_OPEN_ABORT_IF_CRASHED | HA_OPEN_DELAY_KEY_WRITE);
unknown's avatar
unknown committed
7357
#ifdef HAVE_QUERY_CACHE
7358 7359 7360 7361 7362
    query_cache_size=0;
#endif
    break;
  case (int) OPT_SAFE:
    opt_specialflag|= SPECIAL_SAFE_MODE;
7363
    delay_key_write_options= DELAY_KEY_WRITE_NONE;
7364 7365
    myisam_recover_options= HA_RECOVER_DEFAULT;
    ha_open_options&= ~(HA_OPEN_DELAY_KEY_WRITE);
7366 7367 7368
    break;
  case (int) OPT_SKIP_PRIOR:
    opt_specialflag|= SPECIAL_NO_PRIOR;
7369
    sql_print_warning("The --skip-thread-priority startup option is deprecated "
Konstantin Osipov's avatar
Konstantin Osipov committed
7370 7371
                      "and will be removed in MySQL 7.0. This option has no effect "
                      "as the implied behavior is already the default.");
7372
    break;
7373 7374 7375 7376
  case (int) OPT_SKIP_HOST_CACHE:
    opt_specialflag|= SPECIAL_NO_HOST_CACHE;
    break;
  case (int) OPT_SKIP_RESOLVE:
7377
    opt_skip_name_resolve= 1;
7378 7379 7380 7381 7382 7383 7384 7385 7386 7387
    opt_specialflag|=SPECIAL_NO_RESOLVE;
    break;
  case (int) OPT_WANT_CORE:
    test_flags |= TEST_CORE_ON_SIGNAL;
    break;
  case (int) OPT_SKIP_STACK_TRACE:
    test_flags|=TEST_NO_STACKTRACE;
    break;
  case (int) OPT_BIND_ADDRESS:
    {
7388 7389 7390 7391 7392 7393 7394
      struct addrinfo *res_lst, hints;    

      bzero(&hints, sizeof(struct addrinfo));
      hints.ai_socktype= SOCK_STREAM;
      hints.ai_protocol= IPPROTO_TCP;

      if (getaddrinfo(argument, NULL, &hints, &res_lst) != 0) 
unknown's avatar
unknown committed
7395
      {
7396 7397
        sql_print_error("Can't start server: cannot resolve hostname!");
        return 1;
unknown's avatar
unknown committed
7398
      }
7399 7400

      if (res_lst->ai_next)
7401
      {
7402
        sql_print_error("Can't start server: bind-address refers to multiple interfaces!");
7403
        return 1;
7404
      }
7405
      freeaddrinfo(res_lst);
7406 7407
    }
    break;
7408 7409 7410 7411
  case OPT_CONSOLE:
    if (opt_console)
      opt_error_log= 0;			// Force logs to stdout
    break;
7412 7413 7414 7415 7416 7417
  case OPT_BOOTSTRAP:
    opt_noacl=opt_bootstrap=1;
    break;
  case OPT_SERVER_ID:
    server_id_supplied = 1;
    break;
unknown's avatar
unknown committed
7418
  case OPT_ONE_THREAD:
7419
    thread_handling= SCHEDULER_ONE_THREAD_PER_CONNECTION;
7420
    break;
unknown's avatar
unknown committed
7421
  case OPT_LOWER_CASE_TABLE_NAMES:
7422
    lower_case_table_names_used= 1;
unknown's avatar
unknown committed
7423
    break;
7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439
#if defined(ENABLED_DEBUG_SYNC)
  case OPT_DEBUG_SYNC_TIMEOUT:
    /*
      Debug Sync Facility. See debug_sync.cc.
      Default timeout for WAIT_FOR action.
      Default value is zero (facility disabled).
      If option is given without an argument, supply a non-zero value.
    */
    if (!argument)
    {
      /* purecov: begin tested */
      opt_debug_sync_timeout= DEBUG_SYNC_DEFAULT_WAIT_TIMEOUT;
      /* purecov: end */
    }
    break;
#endif /* defined(ENABLED_DEBUG_SYNC) */
7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451
  case OPT_ENGINE_CONDITION_PUSHDOWN:
    /*
      The last of --engine-condition-pushdown and --optimizer_switch on
      command line wins (see get_options().
    */
    if (global_system_variables.engine_condition_pushdown)
      global_system_variables.optimizer_switch|=
        OPTIMIZER_SWITCH_ENGINE_CONDITION_PUSHDOWN;
    else
      global_system_variables.optimizer_switch&=
        ~OPTIMIZER_SWITCH_ENGINE_CONDITION_PUSHDOWN;
    break;
7452 7453 7454 7455 7456 7457 7458 7459
  case OPT_LOG_ERROR:
    /*
      "No --log-error" == "write errors to stderr",
      "--log-error without argument" == "write errors to a file".
    */
    if (argument == NULL) /* no argument */
      log_error_file_ptr= const_cast<char*>("");
    break;
unknown's avatar
unknown committed
7460
  }
7461 7462
  return 0;
}
7463

7464

unknown's avatar
unknown committed
7465
/** Handle arguments for multiple key caches. */
7466

7467
C_MODE_START
7468

7469
static void*
7470
mysql_getopt_value(const char *keyname, uint key_length,
7471
		   const struct my_option *option, int *error)
7472
{
7473 7474
  if (error)
    *error= 0;
7475 7476
  switch (option->id) {
  case OPT_KEY_BUFFER_SIZE:
unknown's avatar
unknown committed
7477
  case OPT_KEY_CACHE_BLOCK_SIZE:
7478 7479
  case OPT_KEY_CACHE_DIVISION_LIMIT:
  case OPT_KEY_CACHE_AGE_THRESHOLD:
7480
  {
unknown's avatar
unknown committed
7481
    KEY_CACHE *key_cache;
7482
    if (!(key_cache= get_or_create_key_cache(keyname, key_length)))
7483 7484 7485 7486 7487
    {
      if (error)
        *error= EXIT_OUT_OF_MEMORY;
      return 0;
    }
7488 7489
    switch (option->id) {
    case OPT_KEY_BUFFER_SIZE:
7490
      return &key_cache->param_buff_size;
7491
    case OPT_KEY_CACHE_BLOCK_SIZE:
7492
      return &key_cache->param_block_size;
7493
    case OPT_KEY_CACHE_DIVISION_LIMIT:
7494
      return &key_cache->param_division_limit;
7495
    case OPT_KEY_CACHE_AGE_THRESHOLD:
7496
      return &key_cache->param_age_threshold;
7497
    }
7498 7499
  }
  }
7500
  return option->value;
7501 7502
}

7503
static void option_error_reporter(enum loglevel level, const char *format, ...)
unknown's avatar
unknown committed
7504
{
7505
  va_list args;
unknown's avatar
unknown committed
7506
  va_start(args, format);
7507 7508 7509 7510 7511 7512 7513

  /* Don't print warnings for --loose options during bootstrap */
  if (level == ERROR_LEVEL || !opt_bootstrap ||
      global_system_variables.log_warnings)
  {
    vprint_msg_to_log(level, format, args);
  }
unknown's avatar
unknown committed
7514
  va_end(args);
unknown's avatar
unknown committed
7515
}
7516

7517
C_MODE_END
unknown's avatar
unknown committed
7518

unknown's avatar
unknown committed
7519
/**
Marc Alff's avatar
Marc Alff committed
7520 7521 7522 7523 7524 7525
  Get server options from the command line,
  and perform related server initializations.
  @param [in, out] argc_ptr       command line options (count)
  @param [in, out] argv_ptr       command line options (values)
  @return 0 on success

unknown's avatar
unknown committed
7526 7527 7528
  @todo
  - FIXME add EXIT_TOO_MANY_ARGUMENTS to "mysys_err.h" and return that code?
*/
Marc Alff's avatar
Marc Alff committed
7529
static int get_options(int *argc_ptr, char ***argv_ptr)
7530 7531 7532
{
  int ho_error;

7533
  my_getopt_register_get_addr(mysql_getopt_value);
7534
  my_getopt_error_reporter= option_error_reporter;
unknown's avatar
unknown committed
7535

Marc Alff's avatar
Marc Alff committed
7536 7537 7538 7539
  /* prepare all_options array */
  my_init_dynamic_array(&all_options, sizeof(my_option),
                        array_elements(my_long_options),
                        array_elements(my_long_options)/4);
7540 7541 7542
  for (my_option *opt= my_long_options;
       opt < my_long_options + array_elements(my_long_options) - 1;
       opt++)
Marc Alff's avatar
Marc Alff committed
7543 7544 7545
    insert_dynamic(&all_options, (uchar*) opt);
  sys_var_add_options(&all_options, sys_var::PARSE_NORMAL);
  add_terminator(&all_options);
7546

unknown's avatar
unknown committed
7547 7548 7549
  /* Skip unknown options so that they may be processed later by plugins */
  my_getopt_skip_unknown= TRUE;

Marc Alff's avatar
Marc Alff committed
7550
  if ((ho_error= handle_options(argc_ptr, argv_ptr, (my_option*)(all_options.buffer),
7551
                                mysqld_get_one_option)))
7552
    return ho_error;
7553 7554 7555 7556

  if (!opt_help)
    delete_dynamic(&all_options);

Marc Alff's avatar
Marc Alff committed
7557 7558 7559
  /* Add back the program name handle_options removes */
  (*argc_ptr)++;
  (*argv_ptr)--;
7560

7561 7562 7563 7564 7565 7566
  /*
    Options have been parsed. Now some of them need additional special
    handling, like custom value checking, checking of incompatibilites
    between options, setting of multiple variables, etc.
    Do them here.
  */
7567

7568 7569
  if ((opt_log_slow_admin_statements || opt_log_queries_not_using_indexes ||
       opt_log_slow_slave_statements) &&
7570
      !opt_slow_log)
7571
    sql_print_warning("options --log-slow-admin-statements, --log-queries-not-using-indexes and --log-slow-slave-statements have no effect if --log_slow_queries is not set");
7572

7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621
  if (log_error_file_ptr != disabled_my_option)
    opt_error_log= 1;
  else
    log_error_file_ptr= const_cast<char*>("");

  opt_init_connect.length=strlen(opt_init_connect.str);
  opt_init_slave.length=strlen(opt_init_slave.str);

  if (global_system_variables.low_priority_updates)
    thr_upgraded_concurrent_insert_lock= TL_WRITE_LOW_PRIORITY;

  if (ft_boolean_check_syntax_string((uchar*) ft_boolean_syntax))
  {
    sql_print_error("Invalid ft-boolean-syntax string: %s\n",
                    ft_boolean_syntax);
    return 1;
  }

  if (opt_disable_networking)
  {
#if defined(__NETWARE__)
    sql_print_error("Can't start server: skip-networking option is currently not supported on NetWare");
    return 1;
#endif
    mysqld_port= 0;
  }
  if (opt_skip_show_db)
    opt_specialflag|= SPECIAL_SKIP_SHOW_DB;

  if (myisam_flush)
    flush_time= 0;

#ifdef HAVE_REPLICATION
  if (opt_slave_skip_errors)
    init_slave_skip_errors(opt_slave_skip_errors);
#endif

  if (global_system_variables.max_join_size == HA_POS_ERROR)
    global_system_variables.option_bits|= OPTION_BIG_SELECTS;
  else
    global_system_variables.option_bits&= ~OPTION_BIG_SELECTS;

  if (global_system_variables.option_bits & OPTION_AUTOCOMMIT)
    global_system_variables.option_bits&= ~OPTION_NOT_AUTOCOMMIT;
  else
    global_system_variables.option_bits|= OPTION_NOT_AUTOCOMMIT;

  global_system_variables.sql_mode=
    expand_sql_mode(global_system_variables.sql_mode);
unknown's avatar
unknown committed
7622
#if defined(HAVE_BROKEN_REALPATH)
7623 7624 7625 7626 7627 7628 7629 7630 7631 7632
  my_use_symdir=0;
  my_disable_symlinks=1;
  have_symlink=SHOW_OPTION_NO;
#else
  if (!my_use_symdir)
  {
    my_disable_symlinks=1;
    have_symlink=SHOW_OPTION_DISABLED;
  }
#endif
7633 7634 7635 7636 7637 7638
  if (opt_debugging)
  {
    /* Allow break with SIGINT, no core or stack trace */
    test_flags|= TEST_SIGINT | TEST_NO_STACKTRACE;
    test_flags&= ~TEST_CORE_ON_SIGNAL;
  }
7639
  /* Set global MyISAM variables from delay_key_write_options */
7640
  fix_delay_key_write(0, 0, OPT_GLOBAL);
7641

7642
#ifndef EMBEDDED_LIBRARY
7643 7644
  if (mysqld_chroot)
    set_root(mysqld_chroot);
7645
#else
7646
  thread_handling = SCHEDULER_NO_THREADS;
7647 7648
  max_allowed_packet= global_system_variables.max_allowed_packet;
  net_buffer_length= global_system_variables.net_buffer_length;
7649
#endif
7650 7651
  if (fix_paths())
    return 1;
unknown's avatar
unknown committed
7652

unknown's avatar
unknown committed
7653 7654 7655 7656
  /*
    Set some global variables from the global_system_variables
    In most cases the global variables will not be used
  */
7657
  my_disable_locking= myisam_single_user= test(opt_external_locking == 0);
unknown's avatar
unknown committed
7658
  my_default_record_cache_size=global_system_variables.read_buff_size;
unknown's avatar
unknown committed
7659

7660 7661
  global_system_variables.long_query_time= (ulonglong)
    (global_system_variables.long_query_time_double * 1e6);
7662

7663 7664
  if (opt_short_log_format)
    opt_specialflag|= SPECIAL_SHORT_LOG_FORMAT;
7665

7666
  if (init_global_datetime_format(MYSQL_TIMESTAMP_DATE,
7667
                                  &global_date_format) ||
7668
      init_global_datetime_format(MYSQL_TIMESTAMP_TIME,
7669
                                  &global_time_format) ||
7670
      init_global_datetime_format(MYSQL_TIMESTAMP_DATETIME,
7671
                                  &global_datetime_format))
7672
    return 1;
7673

unknown's avatar
unknown committed
7674 7675 7676
#ifdef EMBEDDED_LIBRARY
  one_thread_scheduler(&thread_scheduler);
#else
7677
  if (thread_handling <= SCHEDULER_ONE_THREAD_PER_CONNECTION)
unknown's avatar
unknown committed
7678
    one_thread_per_connection_scheduler(&thread_scheduler);
7679
  else if (thread_handling == SCHEDULER_NO_THREADS)
unknown's avatar
unknown committed
7680 7681 7682 7683
    one_thread_scheduler(&thread_scheduler);
  else
    pool_of_threads_scheduler(&thread_scheduler);  /* purecov: tested */
#endif
7684 7685 7686 7687 7688

  global_system_variables.engine_condition_pushdown=
    test(global_system_variables.optimizer_switch &
         OPTIMIZER_SWITCH_ENGINE_CONDITION_PUSHDOWN);

7689
  return 0;
unknown's avatar
unknown committed
7690 7691 7692
}


7693 7694 7695 7696 7697 7698 7699 7700 7701 7702
/*
  Create version name for running mysqld version
  We automaticly add suffixes -debug, -embedded and -log to the version
  name to make the version more descriptive.
  (MYSQL_SERVER_SUFFIX is set by the compilation environment)
*/

static void set_server_version(void)
{
  char *end= strxmov(server_version, MYSQL_SERVER_VERSION,
7703
                     MYSQL_SERVER_SUFFIX_STR, NullS);
7704 7705 7706 7707
#ifdef EMBEDDED_LIBRARY
  end= strmov(end, "-embedded");
#endif
#ifndef DBUG_OFF
7708
  if (!strstr(MYSQL_SERVER_SUFFIX_STR, "-debug"))
7709 7710
    end= strmov(end, "-debug");
#endif
7711
  if (opt_log || opt_slow_log || opt_bin_log)
7712 7713 7714 7715
    strmov(end, "-log");                        // This may slow down system
}


unknown's avatar
unknown committed
7716 7717 7718
static char *get_relative_path(const char *path)
{
  if (test_if_hard_path(path) &&
7719
      is_prefix(path,DEFAULT_MYSQL_HOME) &&
unknown's avatar
unknown committed
7720 7721
      strcmp(DEFAULT_MYSQL_HOME,FN_ROOTDIR))
  {
unknown's avatar
unknown committed
7722
    path+=(uint) strlen(DEFAULT_MYSQL_HOME);
7723
    while (*path == FN_LIBCHAR || *path == FN_LIBCHAR2)
unknown's avatar
unknown committed
7724 7725 7726 7727 7728 7729
      path++;
  }
  return (char*) path;
}


unknown's avatar
unknown committed
7730
/**
7731 7732
  Fix filename and replace extension where 'dir' is relative to
  mysql_real_data_home.
unknown's avatar
unknown committed
7733 7734
  @return
    1 if len(path) > FN_REFLEN
7735 7736 7737
*/

bool
7738
fn_format_relative_to_data_home(char * to, const char *name,
7739 7740 7741 7742 7743 7744 7745 7746 7747 7748
				const char *dir, const char *extension)
{
  char tmp_path[FN_REFLEN];
  if (!test_if_hard_path(dir))
  {
    strxnmov(tmp_path,sizeof(tmp_path)-1, mysql_real_data_home,
	     dir, NullS);
    dir=tmp_path;
  }
  return !fn_format(to, name, dir, extension,
7749
		    MY_APPEND_EXT | MY_UNPACK_FILENAME | MY_SAFE_PATH);
7750 7751 7752
}


7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772
/**
  Test a file path to determine if the path is compatible with the secure file
  path restriction.
 
  @param path null terminated character string

  @return
    @retval TRUE The path is secure
    @retval FALSE The path isn't secure
*/

bool is_secure_file_path(char *path)
{
  char buff1[FN_REFLEN], buff2[FN_REFLEN];
  /*
    All paths are secure if opt_secure_file_path is 0
  */
  if (!opt_secure_file_priv)
    return TRUE;

Georgi Kodinov's avatar
Georgi Kodinov committed
7773 7774 7775
  if (strlen(path) >= FN_REFLEN)
    return FALSE;

7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794
  if (my_realpath(buff1, path, 0))
  {
    /*
      The supplied file path might have been a file and not a directory.
    */
    int length= (int)dirname_length(path);
    if (length >= FN_REFLEN)
      return FALSE;
    memcpy(buff2, path, length);
    buff2[length]= '\0';
    if (length == 0 || my_realpath(buff1, buff2, 0))
      return FALSE;
  }
  convert_dirname(buff2, buff1, NullS);
  if (strncmp(opt_secure_file_priv, buff2, strlen(opt_secure_file_priv)))
    return FALSE;
  return TRUE;
}

7795
static int fix_paths(void)
unknown's avatar
unknown committed
7796
{
7797
  char buff[FN_REFLEN],*pos;
7798
  convert_dirname(mysql_home,mysql_home,NullS);
7799
  /* Resolve symlinks to allow 'mysql_home' to be a relative symlink */
7800
  my_realpath(mysql_home,mysql_home,MYF(0));
7801 7802 7803 7804 7805 7806 7807
  /* Ensure that mysql_home ends in FN_LIBCHAR */
  pos=strend(mysql_home);
  if (pos[-1] != FN_LIBCHAR)
  {
    pos[0]= FN_LIBCHAR;
    pos[1]= 0;
  }
7808
  convert_dirname(lc_messages_dir, lc_messages_dir, NullS);
7809
  convert_dirname(mysql_real_data_home,mysql_real_data_home,NullS);
unknown's avatar
unknown committed
7810 7811
  (void) my_load_path(mysql_home,mysql_home,""); // Resolve current dir
  (void) my_load_path(mysql_real_data_home,mysql_real_data_home,mysql_home);
7812
  (void) my_load_path(pidfile_name, pidfile_name_ptr, mysql_real_data_home);
unknown's avatar
unknown committed
7813
  (void) my_load_path(opt_plugin_dir, opt_plugin_dir_ptr ? opt_plugin_dir_ptr :
7814
                                      get_relative_path(PLUGINDIR), mysql_home);
7815
  opt_plugin_dir_ptr= opt_plugin_dir;
unknown's avatar
unknown committed
7816

7817 7818 7819 7820 7821 7822
  my_realpath(mysql_unpacked_real_data_home, mysql_real_data_home, MYF(0));
  mysql_unpacked_real_data_home_len= 
    (int) strlen(mysql_unpacked_real_data_home);
  if (mysql_unpacked_real_data_home[mysql_unpacked_real_data_home_len-1] == FN_LIBCHAR)
    --mysql_unpacked_real_data_home_len;

unknown's avatar
unknown committed
7823
  char *sharedir=get_relative_path(SHAREDIR);
unknown's avatar
unknown committed
7824
  if (test_if_hard_path(sharedir))
unknown's avatar
unknown committed
7825
    strmake(buff,sharedir,sizeof(buff)-1);		/* purecov: tested */
unknown's avatar
unknown committed
7826
  else
unknown's avatar
unknown committed
7827
    strxnmov(buff,sizeof(buff)-1,mysql_home,sharedir,NullS);
7828
  convert_dirname(buff,buff,NullS);
7829
  (void) my_load_path(lc_messages_dir, lc_messages_dir, buff);
unknown's avatar
unknown committed
7830 7831

  /* If --character-sets-dir isn't given, use shared library dir */
7832 7833 7834
  if (charsets_dir)
    strmake(mysql_charsets_dir, charsets_dir, sizeof(mysql_charsets_dir)-1);
  else
unknown's avatar
unknown committed
7835 7836
    strxnmov(mysql_charsets_dir, sizeof(mysql_charsets_dir)-1, buff,
	     CHARSET_DIR, NullS);
unknown's avatar
unknown committed
7837
  (void) my_load_path(mysql_charsets_dir, mysql_charsets_dir, buff);
7838
  convert_dirname(mysql_charsets_dir, mysql_charsets_dir, NullS);
unknown's avatar
unknown committed
7839
  charsets_dir=mysql_charsets_dir;
unknown's avatar
unknown committed
7840

unknown's avatar
unknown committed
7841
  if (init_tmpdir(&mysql_tmpdir_list, opt_mysql_tmpdir))
7842
    return 1;
7843 7844
  if (!opt_mysql_tmpdir)
    opt_mysql_tmpdir= mysql_tmpdir;
unknown's avatar
SCRUM  
unknown committed
7845
#ifdef HAVE_REPLICATION
7846
  if (!slave_load_tmpdir)
7847
    slave_load_tmpdir= mysql_tmpdir;
7848
#endif /* HAVE_REPLICATION */
7849 7850 7851 7852 7853 7854
  /*
    Convert the secure-file-priv option to system format, allowing
    a quick strcmp to check if read or write is in an allowed dir
   */
  if (opt_secure_file_priv)
  {
7855 7856 7857 7858 7859 7860
    if (*opt_secure_file_priv == 0)
    {
      opt_secure_file_priv= 0;
    }
    else
    {
Georgi Kodinov's avatar
Georgi Kodinov committed
7861 7862
      if (strlen(opt_secure_file_priv) >= FN_REFLEN)
        opt_secure_file_priv[FN_REFLEN-1]= '\0';
7863
      if (my_realpath(buff, opt_secure_file_priv, 0))
7864 7865 7866 7867
      {
        sql_print_warning("Failed to normalize the argument for --secure-file-priv.");
        return 1;
      }
7868 7869
      char *secure_file_real_path= (char *)my_malloc(FN_REFLEN, MYF(MY_FAE));
      convert_dirname(secure_file_real_path, buff, NullS);
7870 7871 7872
      my_free(opt_secure_file_priv, MYF(0));
      opt_secure_file_priv= secure_file_real_path;
    }
7873
  }
7874
  
7875
  return 0;
unknown's avatar
unknown committed
7876 7877
}

unknown's avatar
unknown committed
7878 7879
/**
  Check if file system used for databases is case insensitive.
7880

unknown's avatar
unknown committed
7881
  @param dir_name			Directory to test
7882

unknown's avatar
unknown committed
7883
  @retval
7884
    -1  Don't know (Test failed)
unknown's avatar
unknown committed
7885
  @retval
7886
    0   File system is case sensitive
unknown's avatar
unknown committed
7887
  @retval
7888 7889 7890 7891 7892 7893 7894 7895 7896
    1   File system is case insensitive
*/

static int test_if_case_insensitive(const char *dir_name)
{
  int result= 0;
  File file;
  char buff[FN_REFLEN], buff2[FN_REFLEN];
  MY_STAT stat_info;
7897
  DBUG_ENTER("test_if_case_insensitive");
7898 7899 7900 7901 7902

  fn_format(buff, glob_hostname, dir_name, ".lower-test",
	    MY_UNPACK_FILENAME | MY_REPLACE_EXT | MY_REPLACE_DIR);
  fn_format(buff2, glob_hostname, dir_name, ".LOWER-TEST",
	    MY_UNPACK_FILENAME | MY_REPLACE_EXT | MY_REPLACE_DIR);
Marc Alff's avatar
Marc Alff committed
7903 7904 7905
  mysql_file_delete(key_file_casetest, buff2, MYF(0));
  if ((file= mysql_file_create(key_file_casetest,
                               buff, 0666, O_RDWR, MYF(0))) < 0)
7906
  {
7907
    sql_print_warning("Can't create test file %s", buff);
7908
    DBUG_RETURN(-1);
7909
  }
Marc Alff's avatar
Marc Alff committed
7910 7911
  mysql_file_close(file, MYF(0));
  if (mysql_file_stat(key_file_casetest, buff2, &stat_info, MYF(0)))
7912
    result= 1;					// Can access file
Marc Alff's avatar
Marc Alff committed
7913
  mysql_file_delete(key_file_casetest, buff, MYF(MY_WME));
7914 7915
  DBUG_PRINT("exit", ("result: %d", result));
  DBUG_RETURN(result);
7916 7917 7918
}


7919 7920
#ifndef EMBEDDED_LIBRARY

unknown's avatar
unknown committed
7921 7922 7923
/**
  Create file to store pid number.
*/
7924 7925 7926
static void create_pid_file()
{
  File file;
Marc Alff's avatar
Marc Alff committed
7927 7928
  if ((file= mysql_file_create(key_file_pid, pidfile_name, 0664,
                               O_WRONLY | O_TRUNC, MYF(MY_WME))) >= 0)
7929
  {
unknown's avatar
unknown committed
7930
    char buff[21], *end;
7931
    end= int10_to_str((long) getpid(), buff, 10);
unknown's avatar
unknown committed
7932
    *end++= '\n';
Marc Alff's avatar
Marc Alff committed
7933 7934
    if (!mysql_file_write(file, (uchar*) buff, (uint) (end-buff),
                          MYF(MY_WME | MY_NABP)))
7935
    {
Marc Alff's avatar
Marc Alff committed
7936
      mysql_file_close(file, MYF(0));
7937 7938
      return;
    }
Marc Alff's avatar
Marc Alff committed
7939
    mysql_file_close(file, MYF(0));
7940
  }
7941
  sql_perror("Can't start server: can't create PID file");
unknown's avatar
foo1  
unknown committed
7942
  exit(1);
7943
}
7944
#endif /* EMBEDDED_LIBRARY */
7945

unknown's avatar
unknown committed
7946
/** Clear most status variables. */
7947 7948
void refresh_status(THD *thd)
{
Marc Alff's avatar
Marc Alff committed
7949
  mysql_mutex_lock(&LOCK_status);
7950

7951
  /* Add thread's status variabes to global status */
7952
  add_to_status(&global_status_var, &thd->status_var);
7953 7954

  /* Reset thread's status variables */
7955
  bzero((uchar*) &thd->status_var, sizeof(thd->status_var));
7956

7957
  /* Reset some global variables */
unknown's avatar
unknown committed
7958
  reset_status_vars();
7959

7960 7961
  /* Reset the counters of all key caches (default and named). */
  process_key_caches(reset_key_cache_counters);
7962
  flush_status_time= time((time_t*) 0);
Marc Alff's avatar
Marc Alff committed
7963
  mysql_mutex_unlock(&LOCK_status);
7964 7965 7966 7967 7968 7969 7970

  /*
    Set max_used_connections to the number of currently open
    connections.  Lock LOCK_thread_count out of LOCK_status to avoid
    deadlocks.  Status reset becomes not atomic, but status data is
    not exact anyway.
  */
Marc Alff's avatar
Marc Alff committed
7971
  mysql_mutex_lock(&LOCK_thread_count);
7972
  max_used_connections= thread_count-delayed_insert_threads;
Marc Alff's avatar
Marc Alff committed
7973
  mysql_mutex_unlock(&LOCK_thread_count);
7974 7975 7976
}


7977
/*****************************************************************************
unknown's avatar
unknown committed
7978 7979
  Instantiate variables for missing storage engines
  This section should go away soon
7980 7981
*****************************************************************************/

unknown's avatar
unknown committed
7982
/*****************************************************************************
7983
  Instantiate templates
unknown's avatar
unknown committed
7984 7985
*****************************************************************************/

7986
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
unknown's avatar
unknown committed
7987 7988 7989 7990
/* Used templates */
template class I_List<THD>;
template class I_List_iterator<THD>;
template class I_List<i_string>;
7991
template class I_List<i_string_pair>;
7992 7993
template class I_List<Statement>;
template class I_List_iterator<Statement>;
unknown's avatar
unknown committed
7994
#endif
Marc Alff's avatar
Marc Alff committed
7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017

#ifdef HAVE_PSI_INTERFACE
#ifdef HAVE_MMAP
PSI_mutex_key key_PAGE_lock, key_LOCK_sync, key_LOCK_active, key_LOCK_pool;
#endif /* HAVE_MMAP */

#ifdef HAVE_OPENSSL
PSI_mutex_key key_LOCK_des_key_file;
#endif /* HAVE_OPENSSL */

PSI_mutex_key key_BINLOG_LOCK_index, key_BINLOG_LOCK_prep_xids,
  key_delayed_insert_mutex, key_hash_filo_lock, key_LOCK_active_mi,
  key_LOCK_connection_count, key_LOCK_crypt, key_LOCK_delayed_create,
  key_LOCK_delayed_insert, key_LOCK_delayed_status, key_LOCK_error_log,
  key_LOCK_gdl, key_LOCK_global_read_lock, key_LOCK_global_system_variables,
  key_LOCK_lock_db, key_LOCK_manager, key_LOCK_mapped_file,
  key_LOCK_mysql_create_db, key_LOCK_open, key_LOCK_prepared_stmt_count,
  key_LOCK_rpl_status, key_LOCK_server_started, key_LOCK_status,
  key_LOCK_system_variables_hash, key_LOCK_table_share, key_LOCK_thd_data,
  key_LOCK_user_conn, key_LOCK_uuid_generator, key_LOG_LOCK_log,
  key_master_info_data_lock, key_master_info_run_lock,
  key_mutex_slave_reporting_capability_err_lock, key_relay_log_info_data_lock,
  key_relay_log_info_log_space_lock, key_relay_log_info_run_lock,
8018 8019 8020
  key_structure_guard_mutex, key_TABLE_SHARE_LOCK_ha_data,
  key_LOCK_error_messages, key_LOG_INFO_lock, key_LOCK_thread_count,
  key_PARTITION_LOCK_auto_inc;
Marc Alff's avatar
Marc Alff committed
8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070

static PSI_mutex_info all_server_mutexes[]=
{
#ifdef HAVE_MMAP
  { &key_PAGE_lock, "PAGE::lock", 0},
  { &key_LOCK_sync, "TC_LOG_MMAP::LOCK_sync", 0},
  { &key_LOCK_active, "TC_LOG_MMAP::LOCK_active", 0},
  { &key_LOCK_pool, "TC_LOG_MMAP::LOCK_pool", 0},
#endif /* HAVE_MMAP */

#ifdef HAVE_OPENSSL
  { &key_LOCK_des_key_file, "LOCK_des_key_file", PSI_FLAG_GLOBAL},
#endif /* HAVE_OPENSSL */

  { &key_BINLOG_LOCK_index, "MYSQL_BIN_LOG::LOCK_index", 0},
  { &key_BINLOG_LOCK_prep_xids, "MYSQL_BIN_LOG::LOCK_prep_xids", 0},
  { &key_delayed_insert_mutex, "Delayed_insert::mutex", 0},
  { &key_hash_filo_lock, "hash_filo::lock", 0},
  { &key_LOCK_active_mi, "LOCK_active_mi", PSI_FLAG_GLOBAL},
  { &key_LOCK_connection_count, "LOCK_connection_count", PSI_FLAG_GLOBAL},
  { &key_LOCK_crypt, "LOCK_crypt", PSI_FLAG_GLOBAL},
  { &key_LOCK_delayed_create, "LOCK_delayed_create", PSI_FLAG_GLOBAL},
  { &key_LOCK_delayed_insert, "LOCK_delayed_insert", PSI_FLAG_GLOBAL},
  { &key_LOCK_delayed_status, "LOCK_delayed_status", PSI_FLAG_GLOBAL},
  { &key_LOCK_error_log, "LOCK_error_log", PSI_FLAG_GLOBAL},
  { &key_LOCK_gdl, "LOCK_gdl", PSI_FLAG_GLOBAL},
  { &key_LOCK_global_read_lock, "LOCK_global_read_lock", PSI_FLAG_GLOBAL},
  { &key_LOCK_global_system_variables, "LOCK_global_system_variables", PSI_FLAG_GLOBAL},
  { &key_LOCK_lock_db, "LOCK_lock_db", PSI_FLAG_GLOBAL},
  { &key_LOCK_manager, "LOCK_manager", PSI_FLAG_GLOBAL},
  { &key_LOCK_mapped_file, "LOCK_mapped_file", PSI_FLAG_GLOBAL},
  { &key_LOCK_mysql_create_db, "LOCK_mysql_create_db", PSI_FLAG_GLOBAL},
  { &key_LOCK_open, "LOCK_open", PSI_FLAG_GLOBAL},
  { &key_LOCK_prepared_stmt_count, "LOCK_prepared_stmt_count", PSI_FLAG_GLOBAL},
  { &key_LOCK_rpl_status, "LOCK_rpl_status", PSI_FLAG_GLOBAL},
  { &key_LOCK_server_started, "LOCK_server_started", PSI_FLAG_GLOBAL},
  { &key_LOCK_status, "LOCK_status", PSI_FLAG_GLOBAL},
  { &key_LOCK_system_variables_hash, "LOCK_system_variables_hash", PSI_FLAG_GLOBAL},
  { &key_LOCK_table_share, "LOCK_table_share", PSI_FLAG_GLOBAL},
  { &key_LOCK_thd_data, "THD::LOCK_thd_data", 0},
  { &key_LOCK_user_conn, "LOCK_user_conn", PSI_FLAG_GLOBAL},
  { &key_LOCK_uuid_generator, "LOCK_uuid_generator", PSI_FLAG_GLOBAL},
  { &key_LOG_LOCK_log, "LOG::LOCK_log", 0},
  { &key_master_info_data_lock, "Master_info::data_lock", 0},
  { &key_master_info_run_lock, "Master_info::run_lock", 0},
  { &key_mutex_slave_reporting_capability_err_lock, "Slave_reporting_capability::err_lock", 0},
  { &key_relay_log_info_data_lock, "Relay_log_info::data_lock", 0},
  { &key_relay_log_info_log_space_lock, "Relay_log_info::log_space_lock", 0},
  { &key_relay_log_info_run_lock, "Relay_log_info::run_lock", 0},
  { &key_structure_guard_mutex, "Query_cache::structure_guard_mutex", 0},
8071
  { &key_TABLE_SHARE_LOCK_ha_data, "TABLE_SHARE::LOCK_ha_data", 0},
Marc Alff's avatar
Marc Alff committed
8072
  { &key_LOCK_error_messages, "LOCK_error_messages", PSI_FLAG_GLOBAL},
Marc Alff's avatar
Marc Alff committed
8073
  { &key_LOG_INFO_lock, "LOG_INFO::lock", 0},
8074 8075
  { &key_LOCK_thread_count, "LOCK_thread_count", PSI_FLAG_GLOBAL},
  { &key_PARTITION_LOCK_auto_inc, "HA_DATA_PARTITION::LOCK_auto_inc", 0}
Marc Alff's avatar
Marc Alff committed
8076 8077 8078 8079 8080 8081 8082 8083
};

PSI_rwlock_key key_rwlock_LOCK_grant, key_rwlock_LOCK_logger,
  key_rwlock_LOCK_sys_init_connect, key_rwlock_LOCK_sys_init_slave,
  key_rwlock_LOCK_system_variables_hash, key_rwlock_query_cache_query_lock;

static PSI_rwlock_info all_server_rwlocks[]=
{
8084 8085 8086
#if defined (HAVE_OPENSSL) && !defined(HAVE_YASSL)
  { &key_rwlock_openssl, "CRYPTO_dynlock_value::lock", 0},
#endif
Marc Alff's avatar
Marc Alff committed
8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106
  { &key_rwlock_LOCK_grant, "LOCK_grant", PSI_FLAG_GLOBAL},
  { &key_rwlock_LOCK_logger, "LOGGER::LOCK_logger", 0},
  { &key_rwlock_LOCK_sys_init_connect, "LOCK_sys_init_connect", PSI_FLAG_GLOBAL},
  { &key_rwlock_LOCK_sys_init_slave, "LOCK_sys_init_slave", PSI_FLAG_GLOBAL},
  { &key_rwlock_LOCK_system_variables_hash, "LOCK_system_variables_hash", PSI_FLAG_GLOBAL},
  { &key_rwlock_query_cache_query_lock, "Query_cache_query::lock", 0}
};

#ifdef HAVE_MMAP
PSI_cond_key key_PAGE_cond, key_COND_active, key_COND_pool;
#endif /* HAVE_MMAP */

PSI_cond_key key_BINLOG_COND_prep_xids, key_BINLOG_update_cond,
  key_COND_cache_status_changed, key_COND_global_read_lock, key_COND_manager,
  key_COND_refresh, key_COND_rpl_status, key_COND_server_started,
  key_delayed_insert_cond, key_delayed_insert_cond_client,
  key_item_func_sleep_cond, key_master_info_data_cond,
  key_master_info_start_cond, key_master_info_stop_cond,
  key_relay_log_info_data_cond, key_relay_log_info_log_space_cond,
  key_relay_log_info_start_cond, key_relay_log_info_stop_cond,
Marc Alff's avatar
Marc Alff committed
8107 8108
  key_TABLE_SHARE_cond, key_user_level_lock_cond,
  key_COND_thread_count, key_COND_thread_cache, key_COND_flush_thread_cache;
Marc Alff's avatar
Marc Alff committed
8109 8110 8111

static PSI_cond_info all_server_conds[]=
{
Marc Alff's avatar
Marc Alff committed
8112 8113 8114
#if (defined(_WIN32) || defined(HAVE_SMEM)) && !defined(EMBEDDED_LIBRARY)
  { &key_COND_handler_count, "COND_handler_count", PSI_FLAG_GLOBAL},
#endif /* _WIN32 || HAVE_SMEM && !EMBEDDED_LIBRARY */
Marc Alff's avatar
Marc Alff committed
8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138
#ifdef HAVE_MMAP
  { &key_PAGE_cond, "PAGE::cond", 0},
  { &key_COND_active, "TC_LOG_MMAP::COND_active", 0},
  { &key_COND_pool, "TC_LOG_MMAP::COND_pool", 0},
#endif /* HAVE_MMAP */
  { &key_BINLOG_COND_prep_xids, "MYSQL_BIN_LOG::COND_prep_xids", 0},
  { &key_BINLOG_update_cond, "MYSQL_BIN_LOG::update_cond", 0},
  { &key_COND_cache_status_changed, "Query_cache::COND_cache_status_changed", 0},
  { &key_COND_global_read_lock, "COND_global_read_lock", PSI_FLAG_GLOBAL},
  { &key_COND_manager, "COND_manager", PSI_FLAG_GLOBAL},
  { &key_COND_refresh, "COND_refresh", PSI_FLAG_GLOBAL},
  { &key_COND_rpl_status, "COND_rpl_status", PSI_FLAG_GLOBAL},
  { &key_COND_server_started, "COND_server_started", PSI_FLAG_GLOBAL},
  { &key_delayed_insert_cond, "Delayed_insert::cond", 0},
  { &key_delayed_insert_cond_client, "Delayed_insert::cond_client", 0},
  { &key_item_func_sleep_cond, "Item_func_sleep::cond", 0},
  { &key_master_info_data_cond, "Master_info::data_cond", 0},
  { &key_master_info_start_cond, "Master_info::start_cond", 0},
  { &key_master_info_stop_cond, "Master_info::stop_cond", 0},
  { &key_relay_log_info_data_cond, "Relay_log_info::data_cond", 0},
  { &key_relay_log_info_log_space_cond, "Relay_log_info::log_space_cond", 0},
  { &key_relay_log_info_start_cond, "Relay_log_info::start_cond", 0},
  { &key_relay_log_info_stop_cond, "Relay_log_info::stop_cond", 0},
  { &key_TABLE_SHARE_cond, "TABLE_SHARE::cond", 0},
Marc Alff's avatar
Marc Alff committed
8139 8140 8141 8142
  { &key_user_level_lock_cond, "User_level_lock::cond", 0},
  { &key_COND_thread_count, "COND_thread_count", PSI_FLAG_GLOBAL},
  { &key_COND_thread_cache, "COND_thread_cache", PSI_FLAG_GLOBAL},
  { &key_COND_flush_thread_cache, "COND_flush_thread_cache", PSI_FLAG_GLOBAL}
Marc Alff's avatar
Marc Alff committed
8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248
};

PSI_thread_key key_thread_bootstrap, key_thread_delayed_insert,
  key_thread_handle_manager, key_thread_main,
  key_thread_one_connection, key_thread_signal_hand;

static PSI_thread_info all_server_threads[]=
{
#if (defined(_WIN32) || defined(HAVE_SMEM)) && !defined(EMBEDDED_LIBRARY)
  { &key_thread_handle_con_namedpipes, "con_named_pipes", PSI_FLAG_GLOBAL},
#endif /* _WIN32 || HAVE_SMEM && !EMBEDDED_LIBRARY */

#if defined(HAVE_SMEM) && !defined(EMBEDDED_LIBRARY)
  { &key_thread_handle_con_sharedmem, "con_shared_mem", PSI_FLAG_GLOBAL},
#endif /* HAVE_SMEM && !EMBEDDED_LIBRARY */

#if (defined(_WIN32) || defined(HAVE_SMEM)) && !defined(EMBEDDED_LIBRARY)
  { &key_thread_handle_con_sockets, "con_sockets", PSI_FLAG_GLOBAL},
#endif /* _WIN32 || HAVE_SMEM && !EMBEDDED_LIBRARY */

#ifdef __WIN__
  { &key_thread_handle_shutdown, "shutdown", PSI_FLAG_GLOBAL},
#endif /* __WIN__ */

  { &key_thread_bootstrap, "bootstrap", PSI_FLAG_GLOBAL},
  { &key_thread_delayed_insert, "delayed_insert", 0},
  { &key_thread_handle_manager, "manager", PSI_FLAG_GLOBAL},
  { &key_thread_main, "main", PSI_FLAG_GLOBAL},
  { &key_thread_one_connection, "one_connection", 0},
  { &key_thread_signal_hand, "signal_handler", PSI_FLAG_GLOBAL}
};

#ifdef HAVE_MMAP
PSI_file_key key_file_map;
#endif /* HAVE_MMAP */

PSI_file_key key_file_binlog, key_file_binlog_index, key_file_casetest,
  key_file_dbopt, key_file_des_key_file, key_file_ERRMSG, key_select_to_file,
  key_file_fileparser, key_file_frm, key_file_global_ddl_log, key_file_load,
  key_file_loadfile, key_file_log_event_data, key_file_log_event_info,
  key_file_master_info, key_file_misc, key_file_MYSQL_LOG, key_file_partition,
  key_file_pid, key_file_relay_log_info, key_file_send_file, key_file_tclog,
  key_file_trg, key_file_trn, key_file_init;

static PSI_file_info all_server_files[]=
{
#ifdef HAVE_MMAP
  { &key_file_map, "map", 0},
#endif /* HAVE_MMAP */
  { &key_file_binlog, "binlog", 0},
  { &key_file_binlog_index, "binlog_index", 0},
  { &key_file_casetest, "casetest", 0},
  { &key_file_dbopt, "dbopt", 0},
  { &key_file_des_key_file, "des_key_file", 0},
  { &key_file_ERRMSG, "ERRMSG", 0},
  { &key_select_to_file, "select_to_file", 0},
  { &key_file_fileparser, "file_parser", 0},
  { &key_file_frm, "FRM", 0},
  { &key_file_global_ddl_log, "global_ddl_log", 0},
  { &key_file_load, "load", 0},
  { &key_file_loadfile, "LOAD_FILE", 0},
  { &key_file_log_event_data, "log_event_data", 0},
  { &key_file_log_event_info, "log_event_info", 0},
  { &key_file_master_info, "master_info", 0},
  { &key_file_misc, "misc", 0},
  { &key_file_MYSQL_LOG, "MYSQL_LOG", 0},
  { &key_file_partition, "partition", 0},
  { &key_file_pid, "pid", 0},
  { &key_file_relay_log_info, "relay_log_info", 0},
  { &key_file_send_file, "send_file", 0},
  { &key_file_tclog, "tclog", 0},
  { &key_file_trg, "trigger_name", 0},
  { &key_file_trn, "trigger", 0},
  { &key_file_init, "init", 0}
};

/**
  Initialise all the performance schema instrumentation points
  used by the server.
*/
void init_server_psi_keys(void)
{
  const char* category= "sql";
  int count;

  if (PSI_server == NULL)
    return;

  count= array_elements(all_server_mutexes);
  PSI_server->register_mutex(category, all_server_mutexes, count);

  count= array_elements(all_server_rwlocks);
  PSI_server->register_rwlock(category, all_server_rwlocks, count);

  count= array_elements(all_server_conds);
  PSI_server->register_cond(category, all_server_conds, count);

  count= array_elements(all_server_threads);
  PSI_server->register_thread(category, all_server_threads, count);

  count= array_elements(all_server_files);
  PSI_server->register_file(category, all_server_files, count);
}

#endif /* HAVE_PSI_INTERFACE */