summaryrefslogtreecommitdiff
path: root/storage/connect/plugutil.cpp
blob: 6790e7eb45c061646f162636c410c604dd97050b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
/************** PlugUtil C Program Source Code File (.C) ***************/
/*                                                                     */
/* PROGRAM NAME: PLUGUTIL                                              */
/* -------------                                                       */
/*  Version 3.0                                                        */
/*                                                                     */
/* COPYRIGHT:                                                          */
/* ----------                                                          */
/*  (C) Copyright to the author Olivier BERTRAND          1993-2017    */
/*                                                                     */
/* WHAT THIS PROGRAM DOES:                                             */
/* -----------------------                                             */
/*  This program are initialization and utility Plug routines.         */
/*                                                                     */
/* WHAT YOU NEED TO COMPILE THIS PROGRAM:                              */
/* --------------------------------------                              */
/*                                                                     */
/*  REQUIRED FILES:                                                    */
/*  ---------------                                                    */
/*  See Readme.C for a list and description of required SYSTEM files.  */
/*                                                                     */
/*    PLUG.C          - Source code                                    */
/*    GLOBAL.H        - Global declaration file                        */
/*    OPTION.H        - Option declaration file                        */
/*                                                                     */
/*  REQUIRED LIBRARIES:                                                */
/*  -------------------                                                */
/*                                                                     */
/*    OS2.LIB        - OS2 libray                                      */
/*    LLIBCE.LIB     - Protect mode/standard combined large model C    */
/*                     library                                         */
/*                                                                     */
/*  REQUIRED PROGRAMS:                                                 */
/*  ------------------                                                 */
/*                                                                     */
/*    IBM C Compiler                                                   */
/*    IBM Linker                                                       */
/*                                                                     */
/***********************************************************************/

/***********************************************************************/
/*                                                                     */
/*  Include relevant MariaDB header file.                              */
/*                                                                     */
/***********************************************************************/
#include "my_global.h"
#if defined(__WIN__)
//#include <windows.h>
#else
#if defined(UNIX) || defined(UNIV_LINUX)
#include <errno.h>
#include <unistd.h>
//#define __stdcall
#else
#include <dir.h>
#endif
#include <stdarg.h>
#endif

#if defined(WIN)
#include <alloc.h>
#endif
#include <errno.h>                  /* definitions of ERANGE ENOMEM    */
#if !defined(UNIX) && !defined(UNIV_LINUX)
#include <direct.h>                 /* Directory management library    */
#endif

/***********************************************************************/
/*                                                                     */
/*  Include application header files                                   */
/*                                                                     */
/*  global.h     is header containing all global declarations.         */
/*                                                                     */
/***********************************************************************/
#define STORAGE                     /* Initialize global variables     */

#include "osutil.h"
#include "global.h"
#include "plgdbsem.h"
#if defined(NEWMSG)
#include "rcmsg.h"
#endif   // NEWMSG

#if defined(__WIN__)
extern HINSTANCE s_hModule;                   /* Saved module handle    */
#endif   // __WIN__

#if defined(XMSG)
extern char *msg_path;
char *msglang(void);
#endif   // XMSG

/***********************************************************************/
/*                Local Definitions and static variables               */
/***********************************************************************/
typedef struct {
  ushort Segsize;
  ushort Size;
  } AREASIZE;

ACTIVITY defActivity = {            /* Describes activity and language */
  NULL,                             /* Points to user work area(s)     */
 "Unknown"};                        /* Application name                */

#if defined(XMSG) || defined(NEWMSG)
  static char stmsg[200];
#endif   // XMSG  ||         NEWMSG

#if defined(UNIX) || defined(UNIV_LINUX)
#include "rcmsg.h"
#endif   // UNIX

/**************************************************************************/
/*  Tracing output function.                                              */
/**************************************************************************/
void htrc(char const *fmt, ...)
  {
  va_list ap;
  va_start (ap, fmt);


//if (trace == 1)
//  vfprintf(debug, fmt, ap);
//else
    vfprintf(stderr, fmt, ap);

  va_end (ap);
  } // end of htrc

/***********************************************************************/
/*  Plug initialization routine.                                       */
/*  Language points on initial language name and eventual path.        */
/*  Return value is the pointer to the Global structure.               */
/***********************************************************************/
PGLOBAL PlugInit(LPCSTR Language, uint worksize)
{
	PGLOBAL g;

	if (trace(2))
		htrc("PlugInit: Language='%s'\n",
			((!Language) ? "Null" : (char*)Language));

	try {
		g = new GLOBAL;
	} catch (...) {
		fprintf(stderr, MSG(GLOBAL_ERROR), (int)sizeof(GLOBAL));
		return NULL;
	} // end try/catch

	g->Sarea = NULL;
	g->Createas = 0;
	g->Alchecked = 0;
	g->Mrr = 0;
	g->Activityp = NULL;
	g->Xchk = NULL;
	g->N = 0;
	g->More = 0;
	strcpy(g->Message, "");

	/*******************************************************************/
	/*  Allocate the main work segment.                                */
	/*******************************************************************/
	if (worksize && AllocSarea(g, worksize)) {
		char errmsg[MAX_STR];
		snprintf(errmsg, sizeof(errmsg) - 1, MSG(WORK_AREA), g->Message);
		strcpy(g->Message, errmsg);
	} // endif Sarea

	g->jump_level = -1;   /* New setting to allow recursive call of Plug */
	return(g);
} /* end of PlugInit */

/***********************************************************************/
/*  PlugExit: Terminate Plug operations.                               */
/***********************************************************************/
int PlugExit(PGLOBAL g)
{
	if (g) {
		PDBUSER dup = PlgGetUser(g);

		if (dup)
			free(dup);

		FreeSarea(g);
		delete g;
	}	// endif g

  return 0;
} // end of PlugExit

/***********************************************************************/
/*  Remove the file type from a file name.                             */
/*  Note: this routine is not really implemented for Unix.             */
/***********************************************************************/
LPSTR PlugRemoveType(LPSTR pBuff, LPCSTR FileName)
  {
#if defined(__WIN__)
  char drive[_MAX_DRIVE];
#else
  char *drive = NULL;
#endif
  char direc[_MAX_DIR];
  char fname[_MAX_FNAME];
  char ftype[_MAX_EXT];

  _splitpath(FileName, drive, direc, fname, ftype);

  if (trace(2)) {
    htrc("after _splitpath: FileName=%s\n", FileName);
    htrc("drive=%s dir=%s fname=%s ext=%s\n",
          SVP(drive), direc, fname, ftype);
    } // endif trace

  _makepath(pBuff, drive, direc, fname, "");

  if (trace(2))
    htrc("buff='%s'\n", pBuff);

  return pBuff;
  } // end of PlugRemoveType


BOOL PlugIsAbsolutePath(LPCSTR path)
{
#if defined(__WIN__)
  return ((path[0] >= 'a' && path[0] <= 'z') ||
          (path[0] >= 'A' && path[0] <= 'Z')) && path[1] == ':';
#else
  return path[0] == '/';
#endif
}

/***********************************************************************/
/*  Set the full path of a file relatively to a given path.            */
/*  Note: this routine is not really implemented for Unix.             */
/***********************************************************************/
LPCSTR PlugSetPath(LPSTR pBuff, LPCSTR prefix, LPCSTR FileName, LPCSTR defpath)
  {
  char newname[_MAX_PATH];
  char direc[_MAX_DIR], defdir[_MAX_DIR], tmpdir[_MAX_DIR];
  char fname[_MAX_FNAME];
  char ftype[_MAX_EXT];
#if defined(__WIN__)
  char drive[_MAX_DRIVE], defdrv[_MAX_DRIVE];
#else
  char *drive = NULL, *defdrv = NULL;
#endif

	if (trace(2))
		htrc("prefix=%s fn=%s path=%s\n", prefix, FileName, defpath);

  if (!strncmp(FileName, "//", 2) || !strncmp(FileName, "\\\\", 2)) {
    strcpy(pBuff, FileName);       // Remote file
    return pBuff;
    } // endif

  if (PlugIsAbsolutePath(FileName))
  {
    strcpy(pBuff, FileName); // FileName includes absolute path
    return pBuff;
  } // endif
  
#if !defined(__WIN__)
  if (*FileName == '~') {
    if (_fullpath(pBuff, FileName, _MAX_PATH)) {
      if (trace(2))
        htrc("pbuff='%s'\n", pBuff);

     return pBuff;
    } else
      return FileName;     // Error, return unchanged name
      
    } // endif FileName  
#endif   // !__WIN__
  
  if (prefix && strcmp(prefix, ".") && !PlugIsAbsolutePath(defpath))
  {
    char tmp[_MAX_PATH];
    int len= snprintf(tmp, sizeof(tmp) - 1, "%s%s%s",
                      prefix, defpath, FileName);
    memcpy(pBuff, tmp, (size_t) len);
    pBuff[len]= '\0';
    return pBuff;
  }

  _splitpath(FileName, drive, direc, fname, ftype);

  if (defpath) {
    char c = defpath[strlen(defpath) - 1];

    strcpy(tmpdir, defpath);

    if (c != '/' && c != '\\')
      strcat(tmpdir, "/");

  } else
    strcpy(tmpdir, "./");

  _splitpath(tmpdir, defdrv, defdir, NULL, NULL);

  if (trace(2)) {
    htrc("after _splitpath: FileName=%s\n", FileName);
#if defined(__WIN__)
    htrc("drive=%s dir=%s fname=%s ext=%s\n", drive, direc, fname, ftype);
    htrc("defdrv=%s defdir=%s\n", defdrv, defdir);
#else
    htrc("dir=%s fname=%s ext=%s\n", direc, fname, ftype);
#endif
    } // endif trace

  if (drive && !*drive)
    strcpy(drive, defdrv);

  switch (*direc) {
    case '\0':
      strcpy(direc, defdir);
      break;
    case '\\':
    case '/':
      break;
    default:
      // This supposes that defdir ends with a SLASH
      strcpy(direc, strcat(defdir, direc));
    } // endswitch

  _makepath(newname, drive, direc, fname, ftype);

  if (trace(2))
    htrc("newname='%s'\n", newname);

  if (_fullpath(pBuff, newname, _MAX_PATH)) {
    if (trace(2))
      htrc("pbuff='%s'\n", pBuff);

    return pBuff;
  } else
    return FileName;     // Error, return unchanged name

  } // end of PlugSetPath

#if defined(XMSG)
/***********************************************************************/
/*  PlugGetMessage: get a message from the message file.               */
/***********************************************************************/
char *PlugReadMessage(PGLOBAL g, int mid, char *m)
  {
  char  msgfile[_MAX_PATH], msgid[32], buff[256];
  char *msg;
  FILE *mfile = NULL;

//GetPrivateProfileString("Message", msglang, "Message\\english.msg",
//                                   msgfile, _MAX_PATH, plgini);
//strcat(strcat(strcpy(msgfile, msg_path), msglang()), ".msg");
  strcat(strcpy(buff, msglang()), ".msg");
  PlugSetPath(msgfile, NULL, buff, msg_path);

  if (!(mfile = fopen(msgfile, "rt"))) {
    sprintf(stmsg, "Fail to open message file %s", msgfile);
    goto err;
    } // endif mfile

  for (;;)
    if (!fgets(buff, 256, mfile)) {
      sprintf(stmsg, "Cannot get message %d %s", mid, SVP(m));
      goto fin;
    } else
      if (atoi(buff) == mid)
        break;

  if (sscanf(buff, " %*d %s \"%[^\"]", msgid, stmsg) < 2) {
    // Old message file
    if (!sscanf(buff, " %*d \"%[^\"]", stmsg)) {
      sprintf(stmsg, "Bad message file for %d %s", mid, SVP(m));
      goto fin;
    } else
      m = NULL;

    } // endif sscanf

  if (m && strcmp(m, msgid)) {
    // Message file is out of date
    strcpy(stmsg, m);
    goto fin;
    } // endif m

 fin:
  fclose(mfile);

 err:
  if (g) {
    // Called by STEP
    msg = PlugDup(g, stmsg);
  } else // Called by MSG or PlgGetErrorMsg
    msg =  stmsg;

  return msg;
  } // end of PlugReadMessage

#elif defined(NEWMSG)
/***********************************************************************/
/*  PlugGetMessage: get a message from the resource string table.      */
/***********************************************************************/
char *PlugGetMessage(PGLOBAL g, int mid)
  {
  char *msg;

#if 0 // was !defined(UNIX) && !defined(UNIV_LINUX)
  int   n = LoadString(s_hModule, (uint)mid, (LPTSTR)stmsg, 200);

  if (n == 0) {
    DWORD rc = GetLastError();
    msg = (char*)PlugSubAlloc(g, NULL, 512);   // Extend buf allocation
    n = sprintf(msg, "Message %d, rc=%d: ", mid, rc);
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
                  FORMAT_MESSAGE_IGNORE_INSERTS, NULL, rc, 0,
                  (LPTSTR)(msg + n), 512 - n, NULL);
    return msg;
    } // endif n

#else  // ALL
  if (!GetRcString(mid, stmsg, 200))
    sprintf(stmsg, "Message %d not found", mid);
#endif // ALL

  if (g) {
    // Called by STEP
    msg = PlugDup(g, stmsg);
  } else // Called by MSG or PlgGetErrorMsg
    msg =  stmsg;

  return msg;
  } // end of PlugGetMessage
#endif     // NEWMSG

#if defined(__WIN__)
/***********************************************************************/
/*  Return the line length of the console screen buffer.               */
/***********************************************************************/
short GetLineLength(PGLOBAL g)
  {
  CONSOLE_SCREEN_BUFFER_INFO coninfo;
  HANDLE  hcons = GetStdHandle(STD_OUTPUT_HANDLE);
  BOOL    b = GetConsoleScreenBufferInfo(hcons, &coninfo);

  return (b) ? coninfo.dwSize.X : 0;
  } // end of GetLineLength
#endif   // __WIN__

/***********************************************************************/
/*  Program for memory allocation of work and language areas.          */
/***********************************************************************/
bool AllocSarea(PGLOBAL g, uint size)
{
  /*********************************************************************/
  /*  This is the allocation routine for the WIN32/UNIX/AIX version.   */
  /*********************************************************************/
#if defined(__WIN__)
	if (size >= 1048576)			 // 1M
		g->Sarea = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
	else
#endif
		g->Sarea = malloc(size);

	if (!g->Sarea) {
		sprintf(g->Message, MSG(MALLOC_ERROR), "malloc");
		g->Sarea_Size = 0;
	}	else
		g->Sarea_Size = size;

#if defined(DEVELOPMENT)
	if (true) {
#else
	if (trace(8)) {
#endif
    if (g->Sarea)
      htrc("Work area of %u allocated at %p\n", size, g->Sarea);
    else
      htrc("SareaAlloc: %s\n", g->Message);

  } // endif trace

  return (!g->Sarea);
} // end of AllocSarea

/***********************************************************************/
/*  Program for memory freeing the work area.                          */
/***********************************************************************/
void FreeSarea(PGLOBAL g)
{
	if (g->Sarea) {
#if defined(__WIN__)
		if (g->Sarea_Size >= 1048576)			 // 1M
			VirtualFree(g->Sarea, 0, MEM_RELEASE);
		else
#endif
			free(g->Sarea);

#if defined(DEVELOPMENT)
		if (true)
#else
		if (trace(8))
#endif
			htrc("Freeing Sarea at %p size = %d\n", g->Sarea, g->Sarea_Size);

		g->Sarea = NULL;
		g->Sarea_Size = 0;
	} // endif Sarea

	return;
} // end of FreeSarea

/***********************************************************************/
/*  Program for SubSet initialization of memory pools.                 */
/*  Here there should be some verification done such as validity of    */
/*  the address and size not larger than memory size.                  */
/***********************************************************************/
BOOL PlugSubSet(void *memp, uint size)
  {
  PPOOLHEADER pph = (PPOOLHEADER)memp;

  pph->To_Free = (OFFSET)sizeof(POOLHEADER);
  pph->FreeBlk = size - pph->To_Free;
  return FALSE;
  } /* end of PlugSubSet */

/***********************************************************************/
/*  Use it to export a function that do throwing.                      */
/***********************************************************************/
static void *DoThrow(int n)
{
	throw n;
} /* end of DoThrow */

/***********************************************************************/
/*  Program for sub-allocating one item in a storage area.             */
/*  The simple way things are done here is based on the fact           */
/*  that no freeing of suballocated blocks is permitted in CONNECT.    */
/***********************************************************************/
void *PlugSubAlloc(PGLOBAL g, void *memp, size_t size)
{
	PPOOLHEADER pph;                           /* Points on area header. */

  if (!memp)
    /*******************************************************************/
    /*  Allocation is to be done in the Sarea.                         */
    /*******************************************************************/
    memp = g->Sarea;

  size = ((size + 7) / 8) * 8;       /* Round up size to multiple of 8 */
  pph = (PPOOLHEADER)memp;

  if (trace(16))
    htrc("SubAlloc in %p size=%d used=%d free=%d\n",
          memp, size, pph->To_Free, pph->FreeBlk);

  if ((uint)size > pph->FreeBlk) {   /* Not enough memory left in pool */
    PCSZ pname = "Work";

    sprintf(g->Message,
      "Not enough memory in %s area for request of %u (used=%d free=%d)",
                          pname, (uint)size, pph->To_Free, pph->FreeBlk);

    if (trace(1))
      htrc("PlugSubAlloc: %s\n", g->Message);

    DoThrow(1234);
  } /* endif size OS32 code */

  /*********************************************************************/
  /*  Do the suballocation the simplest way.                           */
  /*********************************************************************/
  memp = MakePtr(memp, pph->To_Free); /* Points to suballocated block  */
  pph->To_Free += (OFFSET)size;       /* New offset of pool free block */
  pph->FreeBlk -= (uint)size;         /* New size   of pool free block */

  if (trace(16))
    htrc("Done memp=%p used=%d free=%d\n",
          memp, pph->To_Free, pph->FreeBlk);

  return (memp);
} /* end of PlugSubAlloc */

/***********************************************************************/
/*  Program for sub-allocating and copying a string in a storage area. */
/***********************************************************************/
char *PlugDup(PGLOBAL g, const char *str)
  {
  if (str) {
    char *sm = (char*)PlugSubAlloc(g, NULL, strlen(str) + 1);

    strcpy(sm, str);
    return sm;
  } else
    return NULL;

  } // end of PlugDup 

#if 0
/***********************************************************************/
/* This routine suballocate a copy of the passed string.               */
/***********************************************************************/
char *PlugDup(PGLOBAL g, const char *str)
  {
  char  *buf;
  size_t len;

  if (str && (len = strlen(str))) {
    buf = (char*)PlugSubAlloc(g, NULL, len + 1);
    strcpy(buf, str);
  } else
    buf = NULL;

  return(buf);
  } /* end of PlugDup */
#endif // 0

/***********************************************************************/
/* This routine makes a pointer from an offset to a memory pointer.    */
/***********************************************************************/
void *MakePtr(void *memp, OFFSET offset)
  {
  return ((offset == 0) ? NULL : &((char *)memp)[offset]);
  } /* end of MakePtr */

/***********************************************************************/
/* This routine makes an offset from a pointer new format.             */
/***********************************************************************/
#if 0
OFFSET MakeOff(void *memp, void *ptr)
  {
  return ((!ptr) ? 0 : (OFFSET)((char *)ptr - (char *)memp));
  } /* end of MakeOff */
#endif
/*--------------------- End of PLUGUTIL program -----------------------*/