• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

polserver / polserver / 20683523304

03 Jan 2026 10:03PM UTC coverage: 60.252% (-0.05%) from 60.298%
20683523304

push

github

web-flow
fixed warning with gcc by splitting the if statement (#843)

1 of 1 new or added line in 1 file covered. (100.0%)

1763 existing lines in 14 files now uncovered.

44251 of 73443 relevant lines covered (60.25%)

507583.53 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.35
/pol-core/pol/pol.cpp
1
/** @file
2
 *
3
 * @par History
4
 * - 2005/02/23 Shinigami: ServSpecOpt DecayItems to enable/disable item decay
5
 * - 2005/04/03 Shinigami: send_feature_enable() call moved from start_client_char()
6
 *                         to send_start() to send before char selection
7
 * - 2005/04/04 Shinigami: added can_delete_character( chr, delete_by )
8
 * - 2005/06/15 Shinigami: ServSpecOpt UseWinLFH to enable/disable Windows XP/2003 low-fragmentation
9
 * Heap
10
 *                         added Check_for_WinXP_or_Win2003() and low_fragmentation_Heap()
11
 * - 2005/06/20 Shinigami: added llog (needs defined MEMORYLEAK)
12
 * - 2005/07/01 Shinigami: removed Check_for_WinXP_or_Win2003() and transformed call of
13
 *                         Use_low_fragmentation_Heap() into Run-Time Dynamic Linking
14
 * - 2005/10/13 Shinigami: added Check_libc_version() and printing a Warning if libc is to old
15
 * - 2005/11/25 Shinigami: PKTBI_BF::TYPE_SESPAM will not block Inactivity-Check
16
 * - 2005/11/28 MuadDib:   Created check_inactivity() bool function to handle checking packets
17
 *                         for ones to be considered "ignored" for inactivity. Returns true if
18
 *                         the packet was one to be ignored.
19
 * - 2005/11/28 MuadDib:   Implemented check_inactivity() function in appropriate place.
20
 * - 2006/03/01 MuadDib:   Added connect = true to start_client_char so char creation can use.
21
 * - 2006/03/03 MuadDib:   Moved all instances of connected = true to start_client_char.
22
 * - 2006/06/03 Shinigami: added little bit more logging @ pthread_create
23
 * - 2006/06/05 Shinigami: added little bit more logging @ Client disconnects by Core
24
 * - 2006/07/05 Shinigami: moved MakeDirectory("log") a little bit up
25
 * - 2006/10/07 Shinigami: FreeBSD fix - changed some __linux__ to __unix__
26
 * - 2007/03/08 Shinigami: added pthread_exit and _endhreadex to close threads
27
 * - 2007/05/06 Shinigami: smaller bugfix in Check_libc_version()
28
 * - 2007/06/17 Shinigami: Pergon-Linux-Release generates file "pol.pid"
29
 * - 2007/07/08 Shinigami: added UO:KR login process
30
 * - 2008/07/08 Turley:    removed Checkpoint "initializing random number generator"
31
 * - 2008/12/17 MuadDub:   Added check when loading Realms for no realms existing.
32
 * - 2009/01/19 Nando:     added unload_aux_services() and unload_packages() to the shutdown cleanup
33
 * - 2009/1/24  MuadDib:   Added read_bannedips_config() and checkpoint for it after loading of
34
 * pol.cfg
35
 * - 2009/07/23 MuadDib:   Updates for MSGOUT naming.
36
 * - 2009/07/31 MuadDib:   xmain_inner(): Force Client Disconnect to initiate cleanup of clients and
37
 * chars, after shutdown,
38
 *                         before other cleanups.
39
 * - 2009/08/01 MuadDib:   Removed send_tech_stuff(), send_betaclient_BF(), just_ignore_message(),
40
 * and ignore_69() due to not used or obsolete.
41
 * - 2009/08/03 MuadDib:   Renaming of MSG_HANDLER_6017 and related, to MSG_HANDLER_V2 for better
42
 * description
43
 *                         Renamed secondary handler class to *_V2 for naming convention
44
 * - 2009/08/14 Turley:    fixed definition of PKTIN_5D
45
 * - 2009/08/19 Turley:    PKTIN_5D clientflag saved in client->UOExpansionFlagClient
46
 * - 2009/09/03 MuadDib:   Relocation of account related cpp/h
47
 *                         Changes for multi related source file relocation
48
 * - 2009/09/15 MuadDib:   Multi registration/unregistration support added.
49
 * - 2009/09/06 Turley:    Changed Version checks to bitfield client->ClientType
50
 * - 2009/09/22 MuadDib:   Fix for lightlevel resets in client during login.
51
 * - 2009/11/19 Turley:    ssopt.core_sends_season & .core_handled_tags - Tomi
52
 * - 2009/12/04 Turley:    Crypto cleanup - Tomi
53
 * - 2010/01/22 Turley:    Speedhack Prevention System
54
 * - 2010/03/28 Shinigami: Transmit Pointer as Pointer and not Int as Pointer within
55
 * decay_thread_shadow
56
 * - 2011/11/12 Tomi:    Added extobj.cfg
57
 */
58

59
#include "pol.h"
60

61
#include <errno.h>
62

63
#include "pol_global_config.h"
64

65
#include "../bscript/bobject.h"
66
#include "../bscript/escriptv.h"
67
#include "../clib/Debugging/ExceptionParser.h"
68
#include "../clib/Program/ProgramConfig.h"
69
#include "../clib/clib_endian.h"
70
#include "../clib/esignal.h"
71
#include "../clib/fileutil.h"
72
#include "../clib/kbhit.h"
73
#include "../clib/logfacility.h"
74
#include "../clib/network/sockets.h"
75
#include "../clib/passert.h"
76
#include "../clib/rawtypes.h"
77
#include "../clib/refptr.h"
78
#include "../clib/stlutil.h"
79
#include "../clib/streamsaver.h"
80
#include "../clib/threadhelp.h"
81
#include "../clib/timer.h"
82
#include "../clib/tracebuf.h"
83
#include "../plib/pkg.h"
84
#include "../plib/systemstate.h"
85
#include "accounts/account.h"
86
#include "base/position.h"
87
#include "checkpnt.h"
88
#include "console.h"
89
#include "core.h"
90
#include "decay.h"
91
#include "extobj.h"
92
#include "fnsearch.h"
93
#include "gameclck.h"
94
#include "globals/network.h"
95
#include "globals/object_storage.h"
96
#include "globals/state.h"
97
#include "globals/uvars.h"
98
#include "item/armor.h"
99
#include "item/equipmnt.h"
100
#include "item/itemdesc.h"
101
#include "loadunld.h"
102
#include "menu.h"
103
#include "mobile/charactr.h"
104
#include "multi/house.h"
105
#include "multi/multi.h"
106
#include "network/cgdata.h"
107
#include "network/client.h"
108
#include "network/clientthread.h"
109
#include "network/clienttransmit.h"
110
#include "network/cliface.h"
111
#include "network/packethelper.h"
112
#include "network/packethooks.h"
113
#include "network/packets.h"
114
#include "network/pktboth.h"
115
#include "network/pktdef.h"
116
#include "network/pktin.h"
117
#include "network/sockio.h"
118
#include "party.h"
119
#include "polclock.h"
120
#include "poldbg.h"
121
#include "polsem.h"
122
#include "polsig.h"
123
#include "polwww.h"
124
#include "profile.h"
125
#include "realms/WorldChangeReasons.h"
126
#include "realms/realm.h"
127
#include "regions/guardrgn.h"
128
#include "regions/miscrgn.h"
129
#include "regions/musicrgn.h"
130
#include "savedata.h"
131
#include "scrdef.h"
132
#include "scrsched.h"
133
#include "sqlscrobj.h"
134
#include "ssopt.h"
135
#include "testing/poltest.h"
136
#include "ufunc.h"
137
#include "uimport.h"
138
#include "uoclient.h"
139
#include "uoscrobj.h"
140
#include "uworld.h"
141

142

143
#ifndef NDEBUG
144
#include "containr.h"
145
#include "mobile/npc.h"
146
#endif
147

148
#ifdef _WIN32
149
#include <process.h>
150

151
#include "../clib/mdump.h"
152
#endif
153

154

155
#include <cstdio>
156
#include <cstring>
157
#include <exception>
158
#include <iosfwd>
159
#include <string>
160

161
#ifdef _MSC_VER
162
#pragma warning( disable : 4127 )  // conditional expression is constant (needed because of FD_SET)
163
#endif
164

165
namespace Pol
166
{
167
namespace Bscript
168
{
169
void display_executor_instances();
170
void display_bobjectimp_instances();
171
}  // namespace Bscript
172
namespace Items
173
{
174
void load_intrinsic_weapons();
175
void allocate_intrinsic_weapon_serials();
176
}  // namespace Items
177
namespace Network
178
{
179
void load_aux_services();
180
void start_aux_services();
181
void read_bannedips_config( bool initial_load );
182
}  // namespace Network
183
namespace Core
184
{
185
void cancel_all_trades();
186
void load_system_hooks();
187
bool load_realms();
188
void InitializeSystemTrayHandling();
189
void ShutdownSystemTrayHandling();
190
void start_uo_client_listeners( void );
191
void start_tasks();
192

193

194
using namespace threadhelp;
195

196
void send_startup( Network::Client* client )
2✔
197
{
198
  Mobile::Character* chr = client->chr;
2✔
199
  Network::PktHelper::PacketOut<Network::PktOut_1B> msg;
2✔
200
  msg->Write<u32>( chr->serial_ext );
2✔
201
  msg->offset += 4;  // u8 unk5, unk6, unk7, unk8
2✔
202
  msg->WriteFlipped<u16>( chr->graphic );
2✔
203
  msg->WriteFlipped<u16>( chr->x() );
2✔
204
  msg->WriteFlipped<u16>( chr->y() );
2✔
205
  msg->offset++;  // u8 unk_15
2✔
206
  msg->Write<s8>( chr->z() );
2✔
207
  msg->Write<u8>( chr->facing );
2✔
208
  msg->offset += 3;  // u8 unk18,unk19,unk20
2✔
209
  msg->Write<u8>( 0x7Fu );
2✔
210
  msg->offset++;     // u8 unk22
2✔
211
  msg->offset += 4;  // u16 map_startx, map_starty
2✔
212
  msg->WriteFlipped<u16>( client->chr->realm()->width() );
2✔
213
  msg->WriteFlipped<u16>( client->chr->realm()->height() );
2✔
214
  msg->offset += 6;  // u8 unk31, unk32, unk33, unk34, unk35, unk36
2✔
215
  msg.Send( client );
2✔
216
}
2✔
217

218
void send_inrange_items( Network::Client* client )
×
219
{
220
  WorldIterator<ItemFilter>::InMaxVisualRange( client->chr,
×
221
                                               [&]( Items::Item* item )
×
222
                                               {
223
                                                 if ( client->chr->in_visual_range( item ) )
×
224
                                                   send_item( client, item );
×
225
                                               } );
×
226
}
×
227

228
void send_inrange_multis( Network::Client* client )
×
229
{
230
  WorldIterator<MultiFilter>::InMaxVisualRange( client->chr,
×
231
                                                [&]( Multi::UMulti* multi )
×
232
                                                {
233
                                                  if ( client->chr->in_visual_range( multi ) )
×
234
                                                    send_multi( client, multi );
×
235
                                                } );
×
236
}
×
237

238
void textcmd_startlog( Network::Client* client );
239
void textcmd_stoplog( Network::Client* client );
240
void start_client_char( Network::Client* client )
2✔
241
{
242
  client->ready = true;
2✔
243
  client->chr->connected( true );
2✔
244

245
  // even if this stuff just gets queued, we still want the client to start
246
  // getting data now.
247
  client->pause();
2✔
248

249
  Multi::UMulti* supporting_multi;
250
  Items::Item* walkon;
251
  short newz;
252
  if ( client->chr->realm()->walkheight( client->chr, client->chr->pos2d(), client->chr->z(), &newz,
2✔
253
                                         &supporting_multi, &walkon ) )
254
  {
255
    client->chr->setposition( Pos4d( client->chr->pos() ).z( static_cast<s8>( newz ) ) );
×
256
    if ( supporting_multi != nullptr )
×
257
    {
258
      supporting_multi->register_object( client->chr );
×
259
      if ( client->chr->registered_multi == 0 )
×
260
      {
261
        client->chr->registered_multi = supporting_multi->serial;
×
262
        supporting_multi->walk_on( client->chr );
×
263
      }
264
    }
265
    else
266
    {
267
      if ( client->chr->registered_multi > 0 )
×
268
      {
269
        Multi::UMulti* multi = system_find_multi( client->chr->registered_multi );
×
270
        if ( multi != nullptr )
×
271
        {
272
          multi->unregister_object( client->chr );
×
273
        }
274
        client->chr->registered_multi = 0;
×
275
      }
276
    }
277
    client->chr->position_changed();
×
278
  }
279

280
  send_startup( client );
2✔
281

282
  send_realm_change( client, client->chr->realm() );
2✔
283
  send_map_difs( client );
2✔
284

285
  if ( settingsManager.ssopt.core_sends_season )
2✔
286
    send_season_info( client );
2✔
287

288
  client->chr->lastpos = Pos4d( 0, 0, 0, nullptr );
2✔
289

290
  client->gd->music_region =
4✔
291
      gamestate.musicdef->getregion( Pos4d( 0, 0, 0, client->chr->realm() ) );
2✔
292
  client->gd->justice_region =
4✔
293
      gamestate.justicedef->getregion( Pos4d( 0, 0, 0, client->chr->realm() ) );
2✔
294
  client->gd->weather_region =
4✔
295
      gamestate.weatherdef->getregion( Pos4d( 0, 0, 0, client->chr->realm() ) );
2✔
296

297
  send_goxyz( client, client->chr );
2✔
298
  client->chr->check_region_changes();
2✔
299

300
  client->chr->send_warmode();
2✔
301
  login_complete( client );
2✔
302
  client->chr->tellmove();
2✔
303

304
  client->chr->check_weather_region_change( true );
2✔
305

306
  if ( settingsManager.ssopt.core_sends_season )
2✔
307
    send_season_info( client );
2✔
308

309
  send_objects_newly_inrange( client );
2✔
310

311
  client->chr->send_highlight();
2✔
312
  send_owncreate( client, client->chr );
2✔
313

314
  send_goxyz( client, client->chr );
2✔
315

316
  client->restart();
2✔
317

318
  client->chr->clear_gotten_item();
2✔
319
  on_loggon_party( client->chr );
2✔
320
  client->chr->send_buffs();
2✔
321

322

323
  //  Moved login_complete higher to prevent weather regions from messing up client
324
  //  spell icon packets(made it look like it was raining spell icons from spellbook if logged
325
  //  into a weather region with rain.
326
  //  login_complete(client);
327
}
2✔
328

329

330
void call_chr_scripts( Mobile::Character* chr, const std::string& root_script_ecl,
7✔
331
                       const std::string& pkg_script_ecl, bool offline = false )
332
{
333
  ScriptDef sd;
7✔
334
  sd.quickconfig( root_script_ecl );
7✔
335

336
  if ( sd.exists() )
7✔
337
  {
338
    call_script( sd, offline ? new Module::EOfflineCharacterRefObjImp( chr )
×
339
                             : new Module::ECharacterRefObjImp( chr ) );
×
340
  }
341

342
  for ( Plib::Packages::iterator itr = Plib::systemstate.packages.begin();
7✔
343
        itr != Plib::systemstate.packages.end(); ++itr )
140✔
344
  {
345
    Plib::Package* pkg = *itr;
133✔
346

347
    sd.quickconfig( pkg, pkg_script_ecl );
133✔
348
    if ( sd.exists() )
133✔
349
    {
350
      call_script( sd, offline ? new Module::EOfflineCharacterRefObjImp( chr )
×
351
                               : new Module::ECharacterRefObjImp( chr ) );
×
352
    }
353
  }
354
}
7✔
355

356
void run_logon_script( Mobile::Character* chr )
2✔
357
{
358
  call_chr_scripts( chr, "scripts/misc/logon.ecl", "logon.ecl" );
2✔
359
}
2✔
360
void run_reconnect_script( Mobile::Character* chr )
×
361
{
362
  call_chr_scripts( chr, "scripts/misc/reconnect.ecl", "reconnect.ecl" );
×
363
}
×
364
bool can_delete_character( Mobile::Character* chr, int delete_by )
3✔
365
{
366
  ScriptDef sd;
3✔
367
  sd.quickconfig( "scripts/misc/candelete.ecl" );
3✔
368

369
  if ( sd.exists() )
3✔
370
  {
371
    return call_script( sd, new Module::EOfflineCharacterRefObjImp( chr ),
×
372
                        new Bscript::BLong( delete_by ) );
×
373
  }
374
  else
375
  {
376
    return true;
3✔
377
  }
378
}
3✔
379
void call_ondelete_scripts( Mobile::Character* chr )
3✔
380
{
381
  call_chr_scripts( chr, "scripts/misc/ondelete.ecl", "ondelete.ecl", true );
3✔
382
}
3✔
383

384
// FIXME: Consider moving most of this into a function, so character
385
// creation can use the same code.
386
void char_select( Network::Client* client, PKTIN_5D* msg )
2✔
387
{
388
  bool reconnecting = false;
2✔
389
  int charidx = cfBEu32( msg->charidx );
2✔
390
  if ( ( charidx >= Plib::systemstate.config.character_slots ) || ( client->acct == nullptr ) ||
4✔
391
       ( client->acct->get_character( charidx ) == nullptr ) )
2✔
392
  {
393
    send_login_error( client, LOGIN_ERROR_MISC );
×
394
    client->Disconnect();
×
395
    return;
×
396
  }
397

398
  Mobile::Character* chosen_char = client->acct->get_character( charidx );
2✔
399

400
  POLLOGLN( "Account {} selecting character {}", client->acct->name(), chosen_char->name() );
2✔
401

402
  if ( Plib::systemstate.config.min_cmdlevel_to_login > chosen_char->cmdlevel() )
2✔
403
  {
404
    POLLOGLN(
×
405
        "Account {} with character {} doesn't fit MinCmdlevelToLogin from pol.cfg. Client "
406
        "disconnected by Core.",
407
        client->acct->name(), chosen_char->name() );
×
408

409
    send_login_error( client, LOGIN_ERROR_MISC );
×
410
    client->Disconnect();
×
411
    return;
×
412
  }
413

414
  // Dave moved this from login.cpp so client cmdlevel can be checked before denying login
415
  if ( ( ( std::count_if( networkManager.clients.begin(), networkManager.clients.end(),
2✔
416
                          clientHasCharacter ) ) >= Plib::systemstate.config.max_clients ) &&
2✔
417
       ( chosen_char->cmdlevel() < Plib::systemstate.config.max_clients_bypass_cmdlevel ) )
×
418
  {
419
    POLLOGLN(
×
420
        "To much clients connected. Check MaximumClients and/or MaximumClientsBypassCmdLevel in "
421
        "pol.cfg.\n"
422
        "Account {} with character {} Client disconnected by Core.",
423
        client->acct->name(), chosen_char->name() );
×
424

425
    send_login_error( client, LOGIN_ERROR_MISC );
×
426
    client->Disconnect();
×
427
    return;
×
428
  }
429

430
  if ( chosen_char->client )
2✔
431
  {
432
    // we're reattaching to a character that is in-game.  If there is still
433
    // a client attached, disconnect it.
434

435
    chosen_char->client->gd->clear();
×
436
    chosen_char->client->forceDisconnect();
×
437
    chosen_char->client->ready = false;
×
438
    chosen_char->client->msgtype_filter = networkManager.disconnected_filter.get();
×
439

440
    // disassociate the objects from each other.
441
    chosen_char->client->acct = nullptr;
×
442
    chosen_char->client->chr = nullptr;
×
443

444
    chosen_char->client = nullptr;
×
445
    reconnecting = true;
×
446
  }
447
  else if ( !Plib::systemstate.config.allow_multi_clients_per_account &&
4✔
448
            client->acct->has_active_characters() )
2✔
449
  {
450
    // We are trying to attach a new character, but AllowMultiCharacters is not set
451
    send_login_error( client, LOGIN_ERROR_OTHER_CHAR_INUSE );
×
452
    client->Disconnect();
×
453
    return;
×
454
  }
455
  else
456
  {
457
    // logging in a character that's offline.
458
    SetCharacterWorldPosition( chosen_char, Realms::WorldChangeReason::PlayerEnter );
2✔
459
    chosen_char->logged_in( true );
2✔
460
  }
461

462
  client->chr = chosen_char;
2✔
463
  chosen_char->client = client;
2✔
464
  chosen_char->acct.set( client->acct );
2✔
465

466
  client->UOExpansionFlagClient = cfBEu32( msg->clientflags );
2✔
467

468
  client->msgtype_filter = networkManager.game_filter.get();
2✔
469
  start_client_char( client );
2✔
470

471
  if ( !chosen_char->lastpos.realm() )
2✔
472
    chosen_char->lastpos = chosen_char->pos();
2✔
473

474
  if ( !reconnecting )
2✔
475
    run_logon_script( chosen_char );
2✔
476
  else
477
    run_reconnect_script( chosen_char );
×
478
}
479

480
void send_client_char_data( Mobile::Character* chr, Network::Client* client );
481
void handle_resync_request( Network::Client* client, PKTBI_22_SYNC* /*msg*/ )
×
482
{
483
  send_goxyz( client, client->chr );
×
484

485
  client->send_pause();  // dave removed force=true 5/10/3, let uoclient.cfg option determine xflow
×
486
                         // packets (else this hangs 4.0.0e clients)
487

488
  Core::WorldIterator<Core::MobileFilter>::InRange( client->chr->pos(), client->chr->los_size(),
×
489
                                                    [&]( Mobile::Character* zonechr )
×
490
                                                    { send_client_char_data( zonechr, client ); } );
×
491

492
  send_inrange_items( client );
×
493
  send_inrange_multis( client );
×
494

495
  client->send_restart();  // dave removed force=true 5/10/3
×
496
}
×
497

498
void restart_all_clients()
35,316,023✔
499
{
500
  if ( !networkManager.uoclient_protocol.EnableFlowControlPackets )
35,316,023✔
501
    return;
35,316,023✔
502
  for ( Clients::iterator itr = networkManager.clients.begin(), end = networkManager.clients.end();
×
503
        itr != end; ++itr )
×
504
  {
505
    Network::Client* client = ( *itr );
×
506
    if ( client->pause_count )
×
507
    {
508
      client->restart();
×
509
    }
510
  }
511
}
512

513
void polclock_checkin()
35,315,926✔
514
{
515
  stateManager.checkin_clock_times_out_at = polclock() + 30 * POLCLOCKS_PER_SEC;
35,315,926✔
516
}
35,315,926✔
517

518
#define clock_t_to_ms( x ) ( x )
519

520
void tasks_thread( void )
2✔
521
{
522
  polclock_t sleeptime;
523
  bool activity;
524
  try
525
  {
526
    while ( !Clib::exit_signalled )
128✔
527
    {
528
      THREAD_CHECKPOINT( tasks, 1 );
126✔
529
      {
530
        PolLock lck;
126✔
531
        polclock_checkin();
126✔
532
        THREAD_CHECKPOINT( tasks, 2 );
126✔
533
        INC_PROFILEVAR( task_passes );
126✔
534
        check_scheduled_tasks( &sleeptime, &activity );
126✔
535
        THREAD_CHECKPOINT( tasks, 3 );
126✔
536
        restart_all_clients();
126✔
537
        THREAD_CHECKPOINT( tasks, 5 );
126✔
538
      }
126✔
539

540
      THREAD_CHECKPOINT( tasks, 6 );
126✔
541
      if ( activity )
126✔
542
        send_pulse();
116✔
543
      else
544
        INC_PROFILEVAR( noactivity_task_passes );
10✔
545
      THREAD_CHECKPOINT( tasks, 7 );
126✔
546

547
      passert( sleeptime > 0 );
126✔
548

549
      TRACEBUF_ADDELEM( "tasks wait_for_pulse now", static_cast<u32>( polclock() ) );
550
      TRACEBUF_ADDELEM( "tasks wait_for_pulse sleeptime", static_cast<u32>( sleeptime ) );
551

552
      THREAD_CHECKPOINT( tasks, 8 );
126✔
553
      tasks_thread_sleep( static_cast<u32>( polclock_t_to_ms( sleeptime ) ) );
126✔
554
      THREAD_CHECKPOINT( tasks, 9 );
126✔
555
    }
556
  }
557
  catch ( const char* msg )
×
558
  {
559
    POLLOGLN( "Tasks Thread exits due to exception: {}", msg );
×
560
    throw;
×
561
  }
×
562
  catch ( std::string& str )
×
563
  {
564
    POLLOGLN( "Tasks Thread exits due to exception: {}", str );
×
565
    throw;
×
566
  }
×
567
  catch ( std::exception& ex )
×
568
  {
569
    POLLOGLN( "Tasks Thread exits due to exception: {}", ex.what() );
×
570
    throw;
×
571
  }
×
572
}
2✔
573

574
void scripts_thread( void )
2✔
575
{
576
  using namespace std::chrono_literals;
577
  polclock_t sleeptime;
578
  bool activity;
579
  while ( !Clib::exit_signalled )
35,315,531✔
580
  {
581
    THREAD_CHECKPOINT( scripts, 0 );
35,315,527✔
582
    {
583
      PolLock lck;
35,315,527✔
584
      polclock_checkin();
35,315,527✔
585
      TRACEBUF_ADDELEM( "scripts thread now", static_cast<u32>( polclock() ) );
586
      INC_PROFILEVAR( script_passes );
35,315,527✔
587
      THREAD_CHECKPOINT( scripts, 1 );
35,315,527✔
588

589
      Tools::HighPerfTimer duration_timer{};
35,315,527✔
590
      step_scripts( &sleeptime, &activity );
35,315,527✔
591
      stateManager.profilevars.script_passes_duration.update( duration_timer.ellapsed() / 1.0us );
35,315,527✔
592

593
      THREAD_CHECKPOINT( scripts, 50 );
35,315,527✔
594

595
      restart_all_clients();
35,315,527✔
596

597
      THREAD_CHECKPOINT( scripts, 52 );
35,315,527✔
598

599
      if ( TaskScheduler::is_dirty() )
35,315,527✔
600
      {
601
        THREAD_CHECKPOINT( scripts, 53 );
390✔
602

603
        wake_tasks_thread();
390✔
604
      }
605
    }
35,315,527✔
606

607
    if ( activity )
35,315,527✔
608
    {
609
      ++stateManager.profilevars.script_passes_activity;
35,315,527✔
610
    }
611
    else
612
    {
UNCOV
613
      ++stateManager.profilevars.script_passes_noactivity;
×
614
    }
615

616
    if ( sleeptime )
35,315,527✔
617
    {
UNCOV
618
      THREAD_CHECKPOINT( scripts, 54 );
×
619

UNCOV
620
      wait_for_pulse( static_cast<u32>( polclock_t_to_ms( sleeptime ) ) );
×
621

UNCOV
622
      THREAD_CHECKPOINT( scripts, 55 );
×
623
    }
624
  }
625
}
2✔
626

627
template <class T>
628
inline void Delete( T* p )
629
{
630
  delete p;
631
}
632

633
template <class T>
634
class delete_ob
635
{
636
public:
637
  void operator()( T* p ) { delete p; }
638
};
639

640
void reap_thread( void )
2✔
641
{
642
  while ( !Clib::exit_signalled )
57✔
643
  {
644
    {
645
      PolLock lck;
55✔
646
      polclock_checkin();
55✔
647
      objStorageManager.objecthash.Reap();
55✔
648
      for ( auto& item : gamestate.dynamic_item_descriptors )
58✔
649
      {
650
        delete item;
3✔
651
      }
652
      gamestate.dynamic_item_descriptors.clear();
55✔
653
    }
55✔
654

655
    threadhelp::thread_sleep_ms( 2000 );
55✔
656
  }
657
}
2✔
658

659

660
void threadstatus_thread( void )
2✔
661
{
662
  int timeouts_remaining = 1;
2✔
663
  bool sent_wakeups = false;
2✔
664
  // we want this thread to be the last out, so that it can report stuff at shutdown.
665
  while ( !Clib::exit_signalled || threadhelp::child_threads > 1 )
119✔
666
  {
667
    if ( is_polclock_paused_at_zero() )
117✔
668
    {
669
      polclock_t now = polclock();
117✔
670
      if ( now >= stateManager.checkin_clock_times_out_at )
117✔
671
      {
672
        ERROR_PRINTLN(
×
673
            "########################################################\n"
674
            "No clock movement in 30 seconds.  Dumping thread status." );
675
        stateManager.polsig.report_status_signalled = true;
×
676
        stateManager.checkin_clock_times_out_at = now + 30 * POLCLOCKS_PER_SEC;
×
677
      }
678
    }
679

680
    if ( stateManager.polsig.report_status_signalled )
117✔
681
    {
682
      std::string tmp = fmt::format(
683
          "*Thread Info*\n"
684
          "Semaphore TID: {}\n",
685
          locker );
×
686

687
      if ( Plib::systemstate.config.log_traces_when_stuck )
×
688
        Pol::Clib::ExceptionParser::logAllStackTraces();
×
689

690
      fmt::format_to( std::back_inserter( tmp ),
×
691
                      "Scripts Thread Checkpoint: {}\n"
692
                      "Last Script: {} PC: {}\n"
693
                      "Escript Instruction Cycles: {}\n"
694
                      "Tasks Thread Checkpoint: {}\n"
695
                      "Active Client Thread Checkpoint: {}\n"
696
                      "Number of clients: {}\n",
697
                      stateManager.polsig.scripts_thread_checkpoint, Clib::scripts_thread_script,
698
                      Clib::scripts_thread_scriptPC, Bscript::escript_instr_cycles,
699
                      stateManager.polsig.tasks_thread_checkpoint,
700
                      stateManager.polsig.active_client_thread_checkpoint,
701
                      Core::networkManager.clients.size() );
×
702
      for ( const auto& client : Core::networkManager.clients )
×
703
        fmt::format_to( std::back_inserter( tmp ), " {} {} {}\n", client->ipaddrAsString(),
×
704
                        client->acct == nullptr ? "prelogin " : client->acct->name(),
×
705
                        client->session()->checkpoint );
×
706
      if ( stateManager.polsig.check_attack_after_move_function_checkpoint )
×
707
        fmt::format_to( std::back_inserter( tmp ), "check_attack_after_move() Checkpoint: {}\n",
×
708
                        stateManager.polsig.check_attack_after_move_function_checkpoint );
709
      tmp += "Current Threads:\n";
×
710
      ThreadMap::Contents contents;
×
711
      threadmap.CopyContents( contents );
×
712
      for ( ThreadMap::Contents::const_iterator citr = contents.begin(); citr != contents.end();
×
713
            ++citr )
×
714
      {
715
        fmt::format_to( std::back_inserter( tmp ), "{} - {}\n", ( *citr ).first, ( *citr ).second );
×
716
      }
717
      fmt::format_to( std::back_inserter( tmp ),
×
718
                      "Child threads (child_threads): {}\n"
719
                      "Registered threads (ThreadMap): {}",
720
                      threadhelp::child_threads, contents.size() );
×
721
      stateManager.polsig.report_status_signalled = false;
×
722
      ERROR_PRINTLN( tmp );
×
723
    }
×
724
    if ( Clib::exit_signalled )
117✔
725
    {
726
      if ( !sent_wakeups )
8✔
727
      {
728
        send_pulse();
2✔
729
        wake_tasks_thread();
2✔
730
        networkManager.clientTransmit->Cancel();
2✔
731
#ifdef HAVE_MYSQL
732
        networkManager.sql_service->stop();
2✔
733
#endif
734
        sent_wakeups = true;
2✔
735
      }
736

737
      --timeouts_remaining;
8✔
738
      if ( timeouts_remaining == 0 )
8✔
739
      {
740
        INFO_PRINTLN( "Waiting for {} child threads to exit", threadhelp::child_threads );
2✔
741
        timeouts_remaining = 5;
2✔
742
      }
743
    }
744
    pol_sleep_ms( 1000 );
117✔
745
  }
746
  // cerr << "threadstatus thread exits." << endl;
747
  signal_catch_thread();
2✔
748
}
2✔
749

750
void catch_signals_thread( void );
751
void reload_configuration();
752

753
void console_thread( void )
2✔
754
{
755
#ifndef _WIN32
756
  Clib::KeyboardHook kb;  // local to have a defined deconstruction to uninstall the hook
2✔
757
#endif
758
  while ( !Clib::exit_signalled )
13✔
759
  {
760
    pol_sleep_ms( 1000 );
9✔
761
#ifdef _WIN32
762
    ConsoleCommand::check_console_commands();
763
#else
764
    ConsoleCommand::check_console_commands( &kb );
9✔
765
    if ( stateManager.polsig.reload_configuration_signalled )
9✔
766
    {
767
      PolLock lck;
×
768
      INFO_PRINT( "Reloading configuration..." );
×
769
      stateManager.polsig.reload_configuration_signalled = false;
×
770
      reload_configuration();
×
771
      INFO_PRINTLN( "Done." );
×
772
    }
×
773
#endif
774
  }
775
}
2✔
776

777
void start_threads()
2✔
778
{
779
  threadmap.Register( thread_pid(), "Main" );
2✔
780

781
  if ( Plib::systemstate.config.web_server )
2✔
782
    start_http_server();
2✔
783

784
  checkpoint( "start tasks thread" );
2✔
785
  threadhelp::start_thread( tasks_thread, "Tasks" );
2✔
786
  checkpoint( "start scripts thread" );
2✔
787
  threadhelp::start_thread( scripts_thread, "Scripts" );
2✔
788

789
  if ( settingsManager.ssopt.decay_items )
2✔
790
  {
791
    checkpoint( "start decay thread" );
2✔
792
    threadhelp::start_thread( Decay::decay_thread, "Decay", nullptr );
2✔
793
  }
794
  else
795
  {
796
    checkpoint( "don't start decay thread" );
×
797
  }
798

799
  checkpoint( "start reap thread" );
2✔
800
  threadhelp::start_thread( reap_thread, "Reap" );
2✔
801

802
  checkpoint( "start dbglisten thread" );
2✔
803
  threadhelp::start_thread( debug_listen_thread, "DbgListn" );
2✔
804

805
  checkpoint( "start threadstatus thread" );
2✔
806
  start_thread( threadstatus_thread, "ThreadStatus" );
2✔
807

808
  checkpoint( "start clienttransmit thread" );
2✔
809
  start_thread( Network::ClientTransmitThread, "ClientTransmit" );
2✔
810

811
#ifdef HAVE_MYSQL
812
  checkpoint( "start sql service thread" );
2✔
813
  start_sql_service();
2✔
814
#endif
815
}
2✔
816

817
#if REFPTR_DEBUG
818
unsigned int ref_counted::_ctor_calls;
819
#endif
820

821
void display_unreaped_orphan_instances();
822
void display_reftypes();
823

824
void display_leftover_objects()
3✔
825
{
826
  Bscript::display_executor_instances();
3✔
827
  display_unreaped_orphan_instances();
3✔
828
#if BOBJECTIMP_DEBUG
829
  Bscript::display_bobjectimp_instances();
830
#endif
831
  display_reftypes();
3✔
832
  {
833
    std::ofstream ofs;
3✔
834
    ofs.open( "leftovers.txt", std::ios::out | std::ios::trunc );
3✔
835
    objStorageManager.objecthash.PrintContents( &ofs );
3✔
836
  }
3✔
837
  std::string tmp;
3✔
838
  if ( stateManager.uobjcount.uobject_count != 0 )
3✔
839
    tmp += fmt::format( "Remaining UObjects: {}\n", stateManager.uobjcount.uobject_count );
×
840
  if ( stateManager.uobjcount.ucharacter_count != 0 )
3✔
841
    tmp += fmt::format( "Remaining Mobiles: {}\n", stateManager.uobjcount.ucharacter_count );
×
842
  if ( stateManager.uobjcount.npc_count != 0 )
3✔
843
    tmp += fmt::format( "Remaining NPCs: {}\n", stateManager.uobjcount.npc_count );
×
844
  if ( stateManager.uobjcount.uitem_count != 0 )
3✔
845
    tmp += fmt::format( "Remaining Items: {}\n", stateManager.uobjcount.uitem_count );
×
846
  if ( stateManager.uobjcount.umulti_count != 0 )
3✔
847
    tmp += fmt::format( "Remaining Multis: {}\n", stateManager.uobjcount.umulti_count );
×
848
  if ( stateManager.uobjcount.unreaped_orphans != 0 )
3✔
849
    tmp += fmt::format( "Unreaped orphans: {}\n", stateManager.uobjcount.unreaped_orphans );
×
850
  if ( stateManager.uobjcount.uobj_count_echrref != 0 )
3✔
851
    tmp +=
852
        fmt::format( "Remaining EChrRef objects: {}\n", stateManager.uobjcount.uobj_count_echrref );
×
853
  if ( Bscript::executor_count )
3✔
854
    tmp += fmt::format( "Remaining Executors: {}\n", Bscript::executor_count );
×
855
  if ( Bscript::eobject_imp_count )
3✔
856
    tmp += fmt::format( "Remaining script objectimps: {}\n", Bscript::eobject_imp_count );
×
857
  INFO_PRINT( tmp );
3✔
858
}
3✔
859

860
void run_start_scripts()
2✔
861
{
862
  INFO_PRINTLN( "Running startup script." );
2✔
863
  run_script_to_completion( "start" );
2✔
864
  for ( const auto& pkg : Plib::systemstate.packages )
40✔
865
  {
866
    std::string scriptname = pkg->dir() + "start.ecl";
38✔
867

868
    if ( Clib::FileExists( scriptname.c_str() ) )
38✔
869
    {
870
      ScriptDef script( "start", pkg, "" );
×
871
      Bscript::BObject obj( run_script_to_completion( script ) );
×
872
    }
×
873
  }
38✔
874
  INFO_PRINTLN( "Startup script complete." );
2✔
875
}
2✔
876

877
#ifdef _WIN32
878
typedef BOOL( WINAPI* DynHeapSetInformation )( PVOID HeapHandle,
879
                                               HEAP_INFORMATION_CLASS HeapInformationClass,
880
                                               PVOID HeapInformation,
881
                                               SIZE_T HeapInformationLength );
882

883
const char* Use_low_fragmentation_Heap()
884
{
885
  if ( settingsManager.ssopt.use_win_lfh )
886
  {
887
    HINSTANCE hKernel32;
888

889
    hKernel32 = LoadLibrary( "Kernel32" );
890
    if ( hKernel32 != nullptr )
891
    {
892
      DynHeapSetInformation ProcAdd;
893
      ProcAdd = (DynHeapSetInformation)GetProcAddress( hKernel32, "HeapSetInformation" );
894
      if ( ProcAdd != nullptr )
895
      {
896
        ULONG HeapFragValue = 2;
897

898
        if ( (ProcAdd)( GetProcessHeap(), HeapCompatibilityInformation, &HeapFragValue,
899
                        sizeof( HeapFragValue ) ) )
900
        {
901
          FreeLibrary( hKernel32 );
902
          return "low-fragmentation Heap ...activated";
903
        }
904
        else
905
        {
906
          FreeLibrary( hKernel32 );
907
          return "low-fragmentation Heap ...not activated";
908
        }
909
      }
910
      else
911
      {
912
        FreeLibrary( hKernel32 );
913
        return "low-fragmentation Heap ...not available on your Windows";
914
      }
915
    }
916
    else
917
      return "low-fragmentation Heap ...not available on your Windows";
918
  }
919
  else
920
    return "low-fragmentation Heap ...disabled via ServSpecOpt";
921
}
922
#endif
923

924
}  // namespace Core
925

926
int xmain_inner( bool testing )
3✔
927
{
928
#ifdef _WIN32
929
  Clib::MiniDumper::Initialize();
930
  // Aug. 15, 2006 Austin
931
  // Added atexit() call to remove the tray icon.
932
  atexit( Core::ShutdownSystemTrayHandling );
933
#else
934
#ifdef __linux__
935
  std::ofstream polpid;
3✔
936

937
  polpid.open( ( Plib::systemstate.config.pidfile_path + "pol.pid" ).c_str(),
3✔
938
               std::ios::out | std::ios::trunc );
939

940
  if ( polpid.is_open() )
3✔
941
    polpid << Clib::tostring( getpid() );
3✔
942
  else
943
    INFO_PRINTLN( "Cannot create pid file in {}", Plib::systemstate.config.pidfile_path );
×
944

945
  polpid.close();
3✔
946
#endif
947
#endif
948

949
  // problem with order of global construction, threads cannot be registered in the constructor of
950
  // gamestate :(
951
  Core::gamestate.task_thread_pool.init_pool(
9✔
952
      std::max( 2u, std::thread::hardware_concurrency() / 2 ), "generic_task_thread" );
6✔
953

954
  int res;
955

956
  // for profiling:
957
  // chdir( "d:\\pol" );
958
  // PrintAllocationData();
959

960
  Clib::MakeDirectory( "log" );
3✔
961

962
  POLLOG_INFOLN( "POL {} - {}\nCompiled on {}\n{}", POL_VERSION_ID,
3✔
963
                 Clib::ProgramConfig::build_target(), Clib::ProgramConfig::build_datetime(),
6✔
964
                 POL_COPYRIGHT );
965
  if ( testing )
3✔
966
    POLLOG_INFOLN( "TESTING MODE" );
1✔
967

968
#ifndef NDEBUG
969
  POLLOG_INFOLN(
970
      "Sizes: \n"
971
      "   UObject:    {}\n"
972
      "   Item:       {}\n"
973
      "   UContainer: {}\n"
974
      "   Character:  {}\n"
975
      "   Client:     {}\n"
976
      "   NPC:        {}",
977
      sizeof( Core::UObject ), sizeof( Items::Item ), sizeof( Core::UContainer ),
978
      sizeof( Mobile::Character ), sizeof( Network::Client ), sizeof( Mobile::NPC ) );
979

980
#ifdef __unix__
981
#ifdef PTHREAD_THREADS_MAX
982
  POLLOG_INFOLN( "   Max Threads: {}", PTHREAD_THREADS_MAX );
983
#endif
984
#endif
985
  POLLOG_INFOLN( "" );
986
#endif
987
  POLLOG_INFOLN( "Using {} out of {} worldsave threads", Core::gamestate.task_thread_pool.size(),
3✔
988
                 std::thread::hardware_concurrency() );
3✔
989

990
  Core::checkpoint( "installing signal handlers" );
3✔
991
  Core::install_signal_handlers();
3✔
992

993
  Core::checkpoint( "starting POL clocks" );
3✔
994
  Core::start_pol_clocks();
3✔
995
  Core::pause_pol_clocks();
3✔
996

997
  POLLOG_INFOLN( "Reading Configuration." );
3✔
998

999
  Core::stateManager.gflag_in_system_startup = true;
3✔
1000

1001
  Core::checkpoint( "reading pol.cfg" );
3✔
1002
  Plib::systemstate.config.read( true );
3✔
1003
  Core::apply_polcfg( true );
3✔
1004

1005
  Core::checkpoint( "reading config/bannedips.cfg" );
3✔
1006
  Network::read_bannedips_config( true );
3✔
1007

1008
  Core::checkpoint( "reading servspecopt.cfg" );
3✔
1009
  Core::ServSpecOpt::read_servspecopt();
3✔
1010

1011
  Core::checkpoint( "reading extobj.cfg" );
3✔
1012
  Core::read_extobj();
3✔
1013

1014
#ifdef _WIN32
1015
  Core::checkpoint( Core::Use_low_fragmentation_Heap() );
1016
#endif
1017

1018
  Core::checkpoint( "init default itemdesc defaults" );
3✔
1019
  Core::gamestate.empty_itemdesc->doubleclick_range =
6✔
1020
      Core::settingsManager.ssopt.default_doubleclick_range;
3✔
1021
  Core::gamestate.empty_itemdesc->decay_time = Core::settingsManager.ssopt.default_decay_time;
3✔
1022

1023
  Core::checkpoint( "loading POL map file" );
3✔
1024
  if ( !Core::load_realms() )
3✔
1025
  {
1026
    POLLOG_ERRORLN(
×
1027
        "Unable to load Realms. Please make sure your Realms have been generated by "
1028
        "UOConvert and your RealmDataPath is set correctly in Pol.cfg." );
1029
    return 1;
×
1030
  }
1031

1032
  // PrintAllocationData();
1033

1034
  Core::checkpoint( "initializing IPC structures" );
3✔
1035
  Core::init_ipc_vars();
3✔
1036
  threadhelp::init_threadhelp();
3✔
1037

1038
#ifdef _WIN32
1039
  Core::InitializeSystemTrayHandling();
1040
#endif
1041

1042
  Core::checkpoint( "initializing sockets library" );
3✔
1043
  res = Network::init_sockets_library();
3✔
1044
  if ( res < 0 )
3✔
1045
  {
1046
    POLLOG_ERRORLN( "Unable to initialize sockets library." );
×
1047
    return 1;
×
1048
  }
1049

1050
  Core::checkpoint( "loading configuration" );
3✔
1051
  Core::load_data();
3✔
1052

1053
  Core::checkpoint( "loading system hooks" );
3✔
1054
  Core::load_system_hooks();
3✔
1055

1056
  Core::checkpoint( "loading packet hooks" );
3✔
1057
  Network::load_packet_hooks();
3✔
1058

1059
  Core::checkpoint( "loading auxservice configuration" );
3✔
1060
  Network::load_aux_services();
3✔
1061

1062
  Core::checkpoint( "reading menus" );
3✔
1063
  Core::Menu::read_menus();
3✔
1064

1065
  Core::checkpoint( "loading intrinsic weapons" );
3✔
1066
  Items::load_intrinsic_weapons();
3✔
1067
  Core::checkpoint( "validating intrinsic shield template" );
3✔
1068
  Items::validate_intrinsic_shield_template();
3✔
1069
  Core::checkpoint( "reading gameservers" );
3✔
1070
  Core::read_gameservers();
3✔
1071
  Core::checkpoint( "reading starting locations" );
3✔
1072
  Core::read_starting_locations();
3✔
1073

1074
  if ( testing )
3✔
1075
  {
1076
    Items::allocate_intrinsic_equipment_serials();
1✔
1077
    Core::stateManager.gflag_in_system_startup = false;
1✔
1078
    POLLOG_INFOLN( "Running POL test suite." );
1✔
1079
    bool res_test = Testing::run_pol_tests();
1✔
1080
    Core::cancel_all_trades();
1✔
1081
    Core::stop_gameclock();
1✔
1082
    Core::gamestate.deinitialize();
1✔
1083
    return !res_test;
1✔
1084
  }
1085

1086
  // PrintAllocationData();
1087
  POLLOG_INFOLN( "Reading data files:" );
2✔
1088
  {
1089
    Tools::Timer<> timer;
2✔
1090
    Core::checkpoint( "reading account data" );
2✔
1091
    Accounts::read_account_data();
2✔
1092

1093
    Core::checkpoint( "reading data" );
2✔
1094
    Core::read_data();
2✔
1095
    POLLOG_INFOLN( "Done! {} milliseconds.", timer.ellapsed() );
2✔
1096
  }
2✔
1097

1098

1099
  Items::allocate_intrinsic_equipment_serials();
2✔
1100
  Core::stateManager.gflag_in_system_startup = false;
2✔
1101

1102
  // PrintAllocationData();
1103

1104
  Core::checkpoint( "running start scripts" );
2✔
1105
  Core::run_start_scripts();
2✔
1106

1107
  Core::checkpoint( "starting client listeners" );
2✔
1108
  Core::start_uo_client_listeners();
2✔
1109

1110
  POLLOG_INFO( "Initialization complete.  POL is active.  Ctrl-C to stop.\n\n" );
2✔
1111

1112
  DEINIT_STARTLOG();
2✔
1113
  POLLOGLN( "{0:s} ({1:s}) compiled on {2:s} running.", "POL ", POL_VERSION_ID,
2✔
1114
            Clib::ProgramConfig::build_target(), Clib::ProgramConfig::build_datetime() );
4✔
1115

1116
  POLLOG_INFOLN( "Game is active." );
2✔
1117

1118
  Core::CoreSetSysTrayToolTip( "Running", Core::ToolTipPrioritySystem );
2✔
1119

1120
  Core::restart_pol_clocks();
2✔
1121
  Core::polclock_checkin();
2✔
1122

1123
  // this is done right after reading globals from pol.txt:
1124
  // checkpoint( "starting game clock" );
1125
  // start_gameclock();
1126

1127
  Core::checkpoint( "starting periodic tasks" );
2✔
1128
  Core::start_tasks();
2✔
1129

1130
  Core::checkpoint( "starting threads" );
2✔
1131
  Core::start_threads();
2✔
1132
  Network::start_aux_services();
2✔
1133
  Core::networkManager.initialize();
2✔
1134

1135
#ifdef _WIN32
1136
  Core::console_thread();
1137
  Core::checkpoint( "exit signal detected" );
1138
  Core::CoreSetSysTrayToolTip( "Shutting down", Core::ToolTipPriorityShutdown );
1139
#else
1140
  // On Linux, signals are directed to a particular thread, if we use pthread_sigmask like we're
1141
  // supposed to.
1142
  // therefore, we have to do this signal checking in this thread.
1143
  threadhelp::start_thread( Core::console_thread, "Console" );
2✔
1144

1145
  Core::catch_signals_thread();
2✔
1146
#endif
1147
  Core::checkpoint( "waiting for child threads to exit" );
2✔
1148
  // NOTE that it's possible that the thread_status thread not have exited yet..
1149
  // it signals the catch_signals_thread (this one) just before it exits.
1150
  // and on windows, we get here right after the console thread exits.
1151
  while ( threadhelp::child_threads )
2✔
1152
  {
1153
    Core::pol_sleep_ms( 1000 );
×
1154
  }
1155
  Core::checkpoint( "child threads have shut down" );
2✔
1156
  Core::cancel_all_trades();
2✔
1157
  Core::stop_gameclock();
2✔
1158
  POLLOG_INFOLN( "Shutting down..." );
2✔
1159

1160
  Core::checkpoint( "writing data" );
2✔
1161
  if ( Core::should_write_data() )
2✔
1162
  {
1163
    Core::CoreSetSysTrayToolTip( "Writing data files", Core::ToolTipPriorityShutdown );
2✔
1164
    POLLOG_INFO( "Writing data files..." );
2✔
1165

1166
    Core::PolLock lck;
2✔
1167
    s64 elapsed_ms;
1168
    Tools::Timer<> timer;
2✔
1169
    auto res_save = Core::write_data( {}, nullptr, nullptr, &elapsed_ms );
2✔
1170
    Core::SaveContext::ready();
2✔
1171
    if ( !res_save || !( *res_save ) )
2✔
1172
      POLLOG_INFOLN( "Data save failed!" );
×
1173
    else
1174
      POLLOG_INFOLN( "Data save completed in {} ms. {} total.", elapsed_ms, timer.ellapsed() );
2✔
1175
  }
2✔
1176
  else
1177
  {
1178
    if ( Clib::passert_shutdown_due_to_assertion && Clib::passert_nosave )
×
1179
      POLLOG_INFOLN( "Not writing data due to assertion failure." );
×
1180
    else if ( Plib::systemstate.config.inhibit_saves )
×
1181
      POLLOG_INFOLN( "Not writing data due to pol.cfg InhibitSaves=1 setting." );
×
1182
  }
1183
  Core::gamestate.deinitialize();
2✔
1184
  return Clib::exit_code;
2✔
1185
}
3✔
1186

1187
int xmain_outer( bool testing )
3✔
1188
{
1189
  try
1190
  {
1191
    return xmain_inner( testing );
3✔
1192
  }
1193
  catch ( std::exception& )
×
1194
  {
1195
    if ( Core::stateManager.last_checkpoint != nullptr )
×
1196
    {
1197
      POLLOG_INFOLN( "Server Shutdown: {}", Core::stateManager.last_checkpoint );
×
1198
      // pol_sleep_ms( 10000 );
1199
    }
1200
    Core::gamestate.deinitialize();
×
1201

1202
    throw;
×
1203
  }
×
1204
}
1205
}  // namespace Pol
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc