diff --git a/libmysqld/lib_sql.cc b/libmysqld/lib_sql.cc
index 94927c590cf8861980bb03babf493ac2a6101174..7d61dbc55f4561b113f18f8f6d635304d2467459 100644
--- a/libmysqld/lib_sql.cc
+++ b/libmysqld/lib_sql.cc
@@ -481,6 +481,10 @@ int init_embedded_server(int argc, char **argv, char **groups)
   char *fake_argv[] = { (char *)"", 0 };
   const char *fake_groups[] = { "server", "embedded", 0 };
   my_bool acl_error;
+
+  if (my_thread_init())
+    return 1;
+
   if (argc)
   {
     argcp= &argc;
diff --git a/sql/derror.cc b/sql/derror.cc
index bf8c589a65faa587bde796403dcd0dbbdeb7a994..db9cd3c0c58b6f0c056b25b421e1b696e0fd46df 100644
--- a/sql/derror.cc
+++ b/sql/derror.cc
@@ -35,6 +35,8 @@ static void init_myfunc_errs(void);
 C_MODE_START
 static const char **get_server_errmsgs()
 {
+  if (!current_thd)
+    return DEFAULT_ERRMSGS;
   return CURRENT_THD_ERRMSGS;
 }
 C_MODE_END
diff --git a/sql/mysqld.cc b/sql/mysqld.cc
index 6dd74eb299ae2f1f7c219cdcece479c241e034bd..840616e0e7c8dec871980ac435bfa4d24e5cba02 100644
--- a/sql/mysqld.cc
+++ b/sql/mysqld.cc
@@ -1486,6 +1486,7 @@ void clean_up(bool print_message)
   cleanup_errmsgs();
   MYSQL_CALLBACK(thread_scheduler, end, ());
   finish_client_errs();
+  (void) my_error_unregister(ER_ERROR_FIRST, ER_ERROR_LAST); // finish server errs
   DBUG_PRINT("quit", ("Error messages freed"));
   /* Tell main we are ready */
   logger.cleanup_end();
diff --git a/sql/set_var.cc b/sql/set_var.cc
index 501c638205601afb2cc73c92c0a0986ba08b7fbe..34b66dea31908afabfa9ba6f339f93f9dd5373db 100644
--- a/sql/set_var.cc
+++ b/sql/set_var.cc
@@ -108,7 +108,7 @@ void sys_var_end()
   my_hash_free(&system_variable_hash);
 
   for (sys_var *var=all_sys_vars.first; var; var= var->next)
-    var->~sys_var();
+    var->cleanup();
 
   DBUG_VOID_RETURN;
 }
diff --git a/sql/set_var.h b/sql/set_var.h
index 5f1f889c4ce17870e89536fe1ba7a029063ea631..ece3b80edb44f1b38b173a73268b188107843403 100644
--- a/sql/set_var.h
+++ b/sql/set_var.h
@@ -92,10 +92,9 @@ class sys_var
           on_check_function on_check_func, on_update_function on_update_func,
           uint deprecated_version, const char *substitute, int parse_flag);
   /**
-    The instance should only be destroyed on shutdown, as it doesn't unlink
-    itself from the chain.
+    All the cleanup procedures should be performed here
   */
-  virtual ~sys_var() {}
+  virtual void cleanup() {}
   /**
     downcast for sys_var_pluginvar. Returns this if it's an instance
     of sys_var_pluginvar, and 0 otherwise.
diff --git a/sql/sys_vars.h b/sql/sys_vars.h
index ee6b429b04a608df80cbcb0eb18e4cd859093517..740c4f03e3e15f8c3650da8c2fe2d72187c27556 100644
--- a/sql/sys_vars.h
+++ b/sql/sys_vars.h
@@ -385,7 +385,7 @@ class Sys_var_charptr: public sys_var
     DBUG_ASSERT(scope() == GLOBAL);
     DBUG_ASSERT(size == sizeof(char *));
   }
-  ~Sys_var_charptr()
+  void cleanup()
   {
     if (flags & ALLOCATED)
       my_free(global_var(char*));