source: trunk/src/helpers/dosh.c@ 154

Last change on this file since 154 was 154, checked in by umoeller, 23 years ago

Misc changes.

  • Property svn:eol-style set to CRLF
  • Property svn:keywords set to Author Date Id Revision
File size: 133.6 KB
Line 
1
2/*
3 *@@sourcefile dosh.c:
4 * dosh.c contains Control Program helper functions.
5 *
6 * This file has miscellaneous system functions,
7 * drive helpers, file helpers, and partition functions.
8 *
9 * Usage: All OS/2 programs.
10 *
11 * Function prefixes (new with V0.81):
12 * -- dosh* Dos (Control Program) helper functions
13 *
14 * These funcs are forward-declared in dosh.h, which
15 * must be #include'd first.
16 *
17 * The resulting dosh.obj object file can be linked
18 * against any application object file. As opposed to
19 * the code in dosh2.c, it does not require any other
20 * code from the helpers.
21 *
22 * dosh.obj can also be used with the VAC subsystem
23 * library (/rn compiler option).
24 *
25 * Note: Version numbering in this file relates to XWorkplace version
26 * numbering.
27 *
28 *@@header "helpers\dosh.h"
29 */
30
31/*
32 * This file Copyright (C) 1997-2000 Ulrich M”ller.
33 * This file is part of the "XWorkplace helpers" source package.
34 * This is free software; you can redistribute it and/or modify
35 * it under the terms of the GNU General Public License as published
36 * by the Free Software Foundation, in version 2 as it comes in the
37 * "COPYING" file of the XWorkplace main distribution.
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
41 * GNU General Public License for more details.
42 */
43
44#define OS2EMX_PLAIN_CHAR
45 // this is needed for "os2emx.h"; if this is defined,
46 // emx will define PSZ as _signed_ char, otherwise
47 // as unsigned char
48
49#define INCL_DOSMODULEMGR
50#define INCL_DOSPROCESS
51#define INCL_DOSEXCEPTIONS
52#define INCL_DOSSESMGR
53#define INCL_DOSQUEUES
54#define INCL_DOSSEMAPHORES
55#define INCL_DOSMISC
56#define INCL_DOSDEVICES
57#define INCL_DOSDEVIOCTL
58#define INCL_DOSERRORS
59
60#define INCL_KBD
61#include <os2.h>
62
63#include <stdlib.h>
64#include <string.h>
65#include <stdio.h>
66#include <stdarg.h>
67#include <ctype.h>
68
69#include "setup.h" // code generation and debugging options
70
71#include "helpers\dosh.h"
72#include "helpers\standards.h"
73
74#pragma hdrstop
75
76// static const CHAR G_acDriveLetters[28] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
77
78/*
79 *@@category: Helpers\Control program helpers\Wrappers
80 */
81
82/* ******************************************************************
83 *
84 * Wrappers
85 *
86 ********************************************************************/
87
88#ifdef DOSH_STANDARDWRAPPERS
89
90 /*
91 *@@ doshSleep:
92 *
93 *@@added V0.9.16 (2002-01-26) [umoeller]
94 */
95
96 APIRET doshSleep(ULONG msec)
97 {
98 // put the call in brackets so the macro won't apply here
99 return (DosSleep)(msec);
100 }
101
102 /*
103 *@@ doshCreateMutexSem:
104 *
105 *@@added V0.9.16 (2002-01-26) [umoeller]
106 */
107
108 APIRET doshCreateMutexSem(PSZ pszName,
109 PHMTX phmtx,
110 ULONG flAttr,
111 BOOL32 fState)
112 {
113 // put the call in brackets so the macro won't apply here
114 return (DosCreateMutexSem)(pszName, phmtx, flAttr, fState);
115 }
116
117 /*
118 *@@ doshRequestMutexSem:
119 *
120 *@@added V0.9.16 (2002-01-26) [umoeller]
121 */
122
123 APIRET doshRequestMutexSem(HMTX hmtx, ULONG ulTimeout)
124 {
125 return (DosRequestMutexSem)(hmtx, ulTimeout);
126 }
127
128 /*
129 *@@ doshReleaseMutexSem:
130 *
131 *@@added V0.9.16 (2002-01-26) [umoeller]
132 */
133
134 APIRET doshReleaseMutexSem(HMTX hmtx)
135 {
136 return (DosReleaseMutexSem)(hmtx);
137 }
138
139 /*
140 *@@ doshSetExceptionHandler:
141 *
142 *@@added V0.9.16 (2002-01-26) [umoeller]
143 */
144
145 APIRET doshSetExceptionHandler(PEXCEPTIONREGISTRATIONRECORD pERegRec)
146 {
147 // put the call in brackets so the macro won't apply here
148 return (DosSetExceptionHandler)(pERegRec);
149 }
150
151 /*
152 *@@ doshUnsetExceptionHandler:
153 *
154 *@@added V0.9.16 (2002-01-26) [umoeller]
155 */
156
157 APIRET doshUnsetExceptionHandler(PEXCEPTIONREGISTRATIONRECORD pERegRec)
158 {
159 // put the call in brackets so the macro won't apply here
160 return (DosUnsetExceptionHandler)(pERegRec);
161 }
162
163#endif
164
165/*
166 *@@category: Helpers\Control program helpers\Miscellaneous
167 * Miscellaneous helpers in dosh.c that didn't fit into any other
168 * category.
169 */
170
171/* ******************************************************************
172 *
173 * Miscellaneous
174 *
175 ********************************************************************/
176
177/*
178 *@@ doshGetChar:
179 * reads a single character from the keyboard.
180 * Useful for VIO sessions, since there's great
181 * confusion between the various C dialects about
182 * how to use getc(), and getc() doesn't work
183 * with the VAC subsystem library.
184 *
185 *@@added V0.9.4 (2000-07-27) [umoeller]
186 */
187
188CHAR doshGetChar(VOID)
189{
190 // CHAR c;
191 // ULONG ulRead = 0;
192
193 KBDKEYINFO kki;
194 KbdCharIn(&kki,
195 0, // wait
196 0);
197
198 return (kki.chChar);
199}
200
201/*
202 *@@ doshQueryShiftState:
203 * returns TRUE if any of the SHIFT keys are
204 * currently pressed. Useful for checks during
205 * WM_COMMAND messages from menus.
206 *
207 *@@changed V0.9.5 (2000-09-27) [umoeller]: added error checking
208 */
209
210BOOL doshQueryShiftState(VOID)
211{
212 BOOL brc = FALSE;
213 APIRET arc = NO_ERROR;
214 HFILE hfKbd;
215 ULONG ulAction;
216
217 if (!(arc = DosOpen("KBD$", &hfKbd, &ulAction, 0,
218 FILE_NORMAL,
219 FILE_OPEN,
220 OPEN_ACCESS_READONLY | OPEN_SHARE_DENYWRITE,
221 (PEAOP2)NULL)))
222 {
223 SHIFTSTATE ShiftState;
224 ULONG cbDataLen = sizeof(ShiftState);
225
226 if (!(arc = DosDevIOCtl(hfKbd, IOCTL_KEYBOARD, KBD_GETSHIFTSTATE,
227 NULL, 0, NULL, // no parameters
228 &ShiftState, cbDataLen, &cbDataLen)))
229 brc = ((ShiftState.fsState & 3) != 0);
230
231 DosClose(hfKbd);
232 }
233
234 return brc;
235}
236
237/*
238 *@@ doshIsWarp4:
239 * checks the OS/2 system version number.
240 *
241 * Returns:
242 *
243 * -- 0 (FALSE): OS/2 2.x or Warp 3 is running.
244 *
245 * -- 1: Warp 4.0 is running.
246 *
247 * -- 2: Warp 4.5 is running (WSeB or Warp 4 FP 13+ or eCS
248 * or ACP/MCP), or even something newer.
249 *
250 *@@changed V0.9.2 (2000-03-05) [umoeller]: reported TRUE on Warp 3 also; fixed
251 *@@changed V0.9.6 (2000-10-16) [umoeller]: patched for speed
252 *@@changed V0.9.9 (2001-04-04) [umoeller]: now returning 2 for Warp 4.5 and above
253 */
254
255ULONG doshIsWarp4(VOID)
256{
257 static BOOL s_fQueried = FALSE;
258 static ULONG s_ulrc = 0;
259
260 if (!s_fQueried)
261 {
262 // first call:
263 ULONG aulBuf[3];
264
265 DosQuerySysInfo(QSV_VERSION_MAJOR, // 11
266 QSV_VERSION_MINOR, // 12
267 &aulBuf, sizeof(aulBuf));
268 // Warp 3 is reported as 20.30
269 // Warp 4 is reported as 20.40
270 // Aurora is reported as 20.45
271
272 if ( (aulBuf[0] > 20) // major > 20; not the case with Warp 3, 4, 5
273 || ( (aulBuf[0] == 20) // major == 20 and minor >= 45
274 && (aulBuf[1] >= 45)
275 )
276 )
277 // Warp 4.5 or newer:
278 s_ulrc = 2;
279 else if ( (aulBuf[0] == 20) // major == 20 and minor == 40
280 && (aulBuf[1] == 40)
281 )
282 // Warp 4:
283 s_ulrc = 1;
284
285 s_fQueried = TRUE;
286 }
287
288 return (s_ulrc);
289}
290
291/*
292 *@@ doshQuerySysErrorMsg:
293 * this retrieves the error message for a system error
294 * (APIRET) from the system error message file (OSO001.MSG).
295 * This file better be on the DPATH (it normally is).
296 *
297 * This returns the string in the "SYSxxx: blahblah" style,
298 * which is normally displayed on the command line when
299 * errors occur.
300 *
301 * The error message is returned in a newly allocated
302 * buffer, which should be free()'d afterwards.
303 *
304 * Returns NULL upon errors.
305 */
306
307PSZ doshQuerySysErrorMsg(APIRET arc) // in: DOS error code
308{
309 PSZ pszReturn = 0;
310 CHAR szDosError[1000];
311 ULONG cbDosError = 0;
312 DosGetMessage(NULL, 0, // no string replacements
313 szDosError, sizeof(szDosError),
314 arc,
315 "OSO001.MSG", // default OS/2 message file
316 &cbDosError);
317 if (cbDosError > 2)
318 {
319 szDosError[cbDosError - 2] = 0;
320 pszReturn = strdup(szDosError);
321 }
322 return (pszReturn);
323}
324
325/*
326 *@@ doshQuerySysUptime:
327 * returns the system uptime in milliseconds.
328 * This can be used for time comparisons.
329 *
330 *@@added V0.9.12 (2001-05-18) [umoeller]
331 */
332
333ULONG doshQuerySysUptime(VOID)
334{
335 ULONG ulms;
336 DosQuerySysInfo(QSV_MS_COUNT,
337 QSV_MS_COUNT,
338 &ulms,
339 sizeof(ulms));
340 return (ulms);
341}
342
343/*
344 *@@ doshDevIOCtl:
345 *
346 * Works with those IOCtls where the buffer
347 * size parameters are always the same anyway,
348 * which applies to all IOCtls I have seen
349 * so far.
350 *
351 *@@added V0.9.13 (2001-06-14) [umoeller]
352 */
353
354APIRET doshDevIOCtl(HFILE hf,
355 ULONG ulCategory,
356 ULONG ulFunction,
357 PVOID pvParams,
358 ULONG cbParams,
359 PVOID pvData,
360 ULONG cbData)
361{
362 return (DosDevIOCtl(hf,
363 ulCategory,
364 ulFunction,
365 pvParams, cbParams, &cbParams,
366 pvData, cbData, &cbData));
367}
368
369/*
370 *@@category: Helpers\Control program helpers\Shared memory management
371 * helpers for allocating and requesting shared memory.
372 */
373
374/* ******************************************************************
375 *
376 * Memory helpers
377 *
378 ********************************************************************/
379
380/*
381 *@@ doshMalloc:
382 * wrapper around malloc() which automatically
383 * sets ERROR_NOT_ENOUGH_MEMORY.
384 *
385 *@@added V0.9.16 (2001-10-19) [umoeller]
386 */
387
388PVOID doshMalloc(ULONG cb,
389 APIRET *parc)
390{
391 PVOID pv;
392 *parc = NO_ERROR;
393 if (!(pv = malloc(cb)))
394 *parc = ERROR_NOT_ENOUGH_MEMORY;
395
396 return (pv);
397}
398
399/*
400 *@@ doshAllocArray:
401 * allocates c * cbArrayItem bytes.
402 * Similar to calloc(), but returns
403 * error codes:
404 *
405 * -- NO_ERROR: *ppv and *pcbAllocated were set.
406 *
407 * -- ERROR_NO_DATA: either c or cbArrayItem are
408 * zero.
409 *
410 * -- ERROR_NOT_ENOUGH_MEMORY: malloc() failed.
411 *
412 *@@added V0.9.16 (2001-12-08) [umoeller]
413 */
414
415APIRET doshAllocArray(ULONG c, // in: array item count
416 ULONG cbArrayItem, // in: size of one array item
417 PBYTE *ppv, // out: memory ptr if NO_ERROR is returned
418 PULONG pcbAllocated) // out: # of bytes allocated
419{
420 if (!c || !cbArrayItem)
421 return ERROR_NO_DATA;
422
423 *pcbAllocated = c * cbArrayItem;
424 if (!(*ppv = (PBYTE)malloc(*pcbAllocated)))
425 return ERROR_NOT_ENOUGH_MEMORY;
426
427 return NO_ERROR;
428}
429
430/*
431 *@@ doshAllocSharedMem:
432 * wrapper for DosAllocSharedMem which has
433 * a malloc()-like syntax. Just due to my
434 * lazyness.
435 *
436 * Note that ulSize is always rounded up to the
437 * next 4KB value, so don't use this hundreds of times.
438 *
439 * Returns NULL upon errors. Possible errors include
440 * that a memory block calle pcszName has already been
441 * allocated.
442 *
443 * Use DosFreeMem(pvrc) to free the memory. The memory
444 * will only be freed if no other process has requested
445 * access.
446 *
447 *@@added V0.9.3 (2000-04-18) [umoeller]
448 */
449
450PVOID doshAllocSharedMem(ULONG ulSize, // in: requested mem block size (rounded up to 4KB)
451 const char* pcszName) // in: name of block ("\\SHAREMEM\\xxx") or NULL
452{
453 PVOID pvrc = NULL;
454 APIRET arc = DosAllocSharedMem((PVOID*)&pvrc,
455 (PSZ)pcszName,
456 ulSize,
457 PAG_COMMIT | PAG_READ | PAG_WRITE);
458 if (arc == NO_ERROR)
459 return (pvrc);
460
461 return (NULL);
462}
463
464/*
465 *@@ doshRequestSharedMem:
466 * requests access to a block of named shared memory
467 * allocated by doshAllocSharedMem.
468 *
469 * Returns NULL upon errors.
470 *
471 * Use DosFreeMem(pvrc) to free the memory. The memory
472 * will only be freed if no other process has requested
473 * access.
474 *
475 *@@added V0.9.3 (2000-04-19) [umoeller]
476 */
477
478PVOID doshRequestSharedMem(PCSZ pcszName)
479{
480 PVOID pvrc = NULL;
481 APIRET arc = DosGetNamedSharedMem((PVOID*)pvrc,
482 (PSZ)pcszName,
483 PAG_READ | PAG_WRITE);
484 if (arc == NO_ERROR)
485 return (pvrc);
486
487 return (NULL);
488}
489
490/*
491 *@@category: Helpers\Control program helpers\Drive management
492 * functions for managing drives... enumerating, testing,
493 * querying etc.
494 */
495
496/* ******************************************************************
497 *
498 * Drive helpers
499 *
500 ********************************************************************/
501
502/*
503 *@@ doshIsFixedDisk:
504 * checks whether a disk is fixed or removeable.
505 * ulLogicalDrive must be 1 for drive A:, 2 for B:, ...
506 * The result is stored in *pfFixed.
507 * Returns DOS error code.
508 *
509 * From my testing, this function does _not_ provoke
510 * "drive not ready" popups, even if the disk is not
511 * ready.
512 *
513 * Warning: This uses DosDevIOCtl, which has proved
514 * to cause problems with some device drivers for
515 * removeable disks.
516 *
517 * Returns:
518 *
519 * -- NO_ERROR: *pfFixed was set.
520 *
521 * -- ERROR_INVALID_DRIVE: drive letter invalid
522 *
523 * -- ERROR_NOT_SUPPORTED (50): for network drives.
524 *
525 *@@changed V0.9.14 (2001-08-03) [umoeller]: added extra fix for A: and B:
526 */
527
528APIRET doshIsFixedDisk(ULONG ulLogicalDrive, // in: 1 for A:, 2 for B:, 3 for C:, ...
529 PBOOL pfFixed) // out: TRUE for fixed disks
530{
531 APIRET arc = ERROR_INVALID_DRIVE;
532
533 if ( (ulLogicalDrive == 1)
534 || (ulLogicalDrive == 2)
535 )
536 {
537 // drive A: and B: can never be fixed V0.9.14 (2001-08-03) [umoeller]
538 *pfFixed = FALSE;
539 return NO_ERROR;
540 }
541
542 if (ulLogicalDrive)
543 {
544 // parameter packet
545 #pragma pack(1)
546 struct {
547 UCHAR command,
548 drive;
549 } parms;
550 #pragma pack()
551
552 // data packet
553 UCHAR ucNonRemoveable;
554
555 parms.drive = (UCHAR)(ulLogicalDrive - 1);
556 if (!(arc = doshDevIOCtl((HFILE)-1,
557 IOCTL_DISK, // 0x08
558 DSK_BLOCKREMOVABLE, // 0x20
559 &parms, sizeof(parms),
560 &ucNonRemoveable, sizeof(ucNonRemoveable))))
561 *pfFixed = (BOOL)ucNonRemoveable;
562 }
563
564 return (arc);
565}
566
567/*
568 *@@ doshQueryDiskParams:
569 * this retrieves more information about a given drive,
570 * which is stored in the specified BIOSPARAMETERBLOCK
571 * structure.
572 *
573 * BIOSPARAMETERBLOCK is defined in the Toolkit headers,
574 * and from my testing, it's the same with the Toolkits
575 * 3 and 4.5.
576 *
577 * If NO_ERROR is returned, the bDeviceType field can
578 * be one of the following (according to CPREF):
579 *
580 * -- 0: 48 TPI low-density diskette drive
581 * -- 1: 96 TPI high-density diskette drive
582 * -- 2: 3.5-inch 720KB diskette drive
583 * -- 3: 8-Inch single-density diskette drive
584 * -- 4: 8-Inch double-density diskette drive
585 * -- 5: Fixed disk
586 * -- 6: Tape drive
587 * -- 7: Other (includes 1.44MB 3.5-inch diskette drive)
588 * -- 8: R/W optical disk
589 * -- 9: 3.5-inch 4.0MB diskette drive (2.88MB formatted)
590 *
591 * From my testing, this function does _not_ provoke
592 * "drive not ready" popups, even if the disk is not
593 * ready.
594 *
595 * Warning: This uses DosDevIOCtl, which has proved
596 * to cause problems with some device drivers for
597 * removeable disks.
598 *
599 * This returns the DOS error code of DosDevIOCtl.
600 * This will be:
601 *
602 * -- NO_ERROR for all local disks;
603 *
604 * -- ERROR_NOT_SUPPORTED (50) for network drives.
605 *
606 *@@added V0.9.0 [umoeller]
607 *@@changed V0.9.13 (2001-06-14) [umoeller]: changed prototype to use BIOSPARAMETERBLOCK directly
608 *@@changed V0.9.13 (2001-06-14) [umoeller]: now querying standard media, no redetermine
609 */
610
611APIRET doshQueryDiskParams(ULONG ulLogicalDrive, // in: 1 for A:, 2 for B:, 3 for C:, ...
612 PBIOSPARAMETERBLOCK pdp) // out: drive parameters
613{
614 APIRET arc = ERROR_INVALID_DRIVE;
615
616 if (ulLogicalDrive)
617 {
618 #pragma pack(1)
619 // parameter packet
620 struct {
621 UCHAR ucCommand,
622 ucDrive;
623 } parms;
624 #pragma pack()
625
626 parms.ucCommand = 0; // 0 = return standard media,
627 // 1 = read currently inserted media
628 // (1 doesn't work any more, returns arc 87
629 // V0.9.13 (2001-06-14) [umoeller])
630 parms.ucDrive=(UCHAR)(ulLogicalDrive-1);
631
632 // zero the structure V0.9.13 (2001-06-14) [umoeller]
633 memset(pdp, 0, sizeof(BIOSPARAMETERBLOCK));
634
635 arc = doshDevIOCtl((HFILE)-1,
636 IOCTL_DISK, // 0x08
637 DSK_GETDEVICEPARAMS, // 0x63
638 &parms, sizeof(parms),
639 pdp, sizeof(BIOSPARAMETERBLOCK));
640
641 /* if (!arc)
642 {
643 _Pmpf((" bDeviceType: %d", pdp->bDeviceType));
644 _Pmpf((" bytes per sector: %d", pdp->usBytesPerSector));
645 _Pmpf((" sectors per track: %d", pdp->usSectorsPerTrack));
646 } */
647 }
648
649 return (arc);
650}
651
652/*
653 *@@ doshQueryDriveType:
654 * tests the specified BIOSPARAMETERBLOCK
655 * for whether it represents a CD-ROM or
656 * some other removeable drive type.
657 *
658 * Returns one of:
659 *
660 * -- DRVTYPE_HARDDISK (0)
661 *
662 * -- DRVTYPE_PARTITIONABLEREMOVEABLE
663 *
664 * -- DRVTYPE_CDROM
665 *
666 * -- DRVTYPE_TAPE
667 *
668 * -- DRVTYPE_VDISK
669 *
670 * -- DRVTYPE_FLOPPY
671 *
672 * -- DRVTYPE_UNKNOWN (255)
673 *
674 * The BIOSPARAMETERBLOCK must be filled
675 * first using doshQueryDiskParams.
676 *
677 *@@added V0.9.16 (2002-01-13) [umoeller]
678 */
679
680BYTE doshQueryDriveType(ULONG ulLogicalDrive,
681 PBIOSPARAMETERBLOCK pdp,
682 BOOL fFixed)
683{
684 if (pdp)
685 {
686 if (pdp->fsDeviceAttr & DEVATTR_PARTITIONALREMOVEABLE) // 0x08
687 return DRVTYPE_PARTITIONABLEREMOVEABLE;
688 else if (fFixed)
689 return DRVTYPE_HARDDISK;
690 else if ( (pdp->bDeviceType == 7) // "other"
691 && (pdp->usBytesPerSector == 2048)
692 && (pdp->usSectorsPerTrack == (USHORT)-1)
693 )
694 return DRVTYPE_CDROM;
695 else switch (pdp->bDeviceType)
696 {
697 case DEVTYPE_TAPE: // 6
698 return DRVTYPE_TAPE;
699
700 case DEVTYPE_48TPI: // 0, 360k 5.25" floppy
701 case DEVTYPE_96TPI: // 1, 1.2M 5.25" floppy
702 case DEVTYPE_35: // 2, 720k 3.5" floppy
703 case DEVTYPE_OTHER: // 7, 1.44 3.5" floppy
704 // 1.84M 3.5" floppy
705 case DEVTYPE_35_288MB:
706 if ( (ulLogicalDrive == 1)
707 || (ulLogicalDrive == 2)
708 )
709 return DRVTYPE_FLOPPY;
710 else
711 return DRVTYPE_VDISK;
712
713 case DEVTYPE_RWOPTICAL: // 8, what is this?!?
714 return DRVTYPE_FLOPPY;
715 }
716 }
717
718 return (DRVTYPE_UNKNOWN);
719}
720
721/*
722 *@@ doshHasAudioCD:
723 * sets *pfAudio to whether ulLogicalDrive
724 * currently has an audio CD inserted.
725 *
726 * Better call this only if you're sure that
727 * ulLogicalDrive is a CD-ROM drive. Use
728 * doshQueryRemoveableType to check.
729 *
730 *@@added V0.9.14 (2001-08-01) [umoeller]
731 */
732
733APIRET doshHasAudioCD(ULONG ulLogicalDrive,
734 HFILE hfDrive, // in: DASD open
735 BOOL fMixedModeCD,
736 PBOOL pfAudio)
737{
738 APIRET arc = NO_ERROR;
739
740 ULONG ulAudioTracks = 0,
741 ulDataTracks = 0;
742
743 CHAR cds1[4] = { 'C', 'D', '0', '1' };
744 CHAR cds2[4];
745
746 *pfAudio = FALSE;
747
748 // check for proper driver signature
749 if (!(arc = doshDevIOCtl(hfDrive,
750 IOCTL_CDROMDISK,
751 CDROMDISK_GETDRIVER,
752 &cds1, sizeof(cds1),
753 &cds2, sizeof(cds2))))
754 {
755 if (memcmp(&cds1, &cds2, 4))
756 // this is not a CD-ROM then:
757 arc = NO_ERROR;
758 else
759 {
760 struct {
761 UCHAR ucFirstTrack,
762 ucLastTrack;
763 ULONG ulLeadOut;
764 } cdat;
765
766 // get track count
767 if (!(arc = doshDevIOCtl(hfDrive,
768 IOCTL_CDROMAUDIO,
769 CDROMAUDIO_GETAUDIODISK,
770 &cds1, sizeof(cds1),
771 &cdat, sizeof(cdat))))
772 {
773 // still no error: build the audio TOC
774 ULONG i;
775 for (i = cdat.ucFirstTrack;
776 i <= cdat.ucLastTrack;
777 i++)
778 {
779 BYTE cdtp[5] =
780 { 'C', 'D', '0', '1', (UCHAR)i };
781
782 struct {
783 ULONG ulTrackAddress;
784 BYTE bFlags;
785 } trackdata;
786
787 if (!(arc = doshDevIOCtl(hfDrive,
788 IOCTL_CDROMAUDIO,
789 CDROMAUDIO_GETAUDIOTRACK,
790 &cdtp, sizeof(cdtp),
791 &trackdata, sizeof(trackdata))))
792 {
793 if (trackdata.bFlags & 64)
794 ulDataTracks++;
795 else
796 {
797 ulAudioTracks++;
798
799 if (!fMixedModeCD)
800 {
801 // caller doesn't want mixed mode:
802 // stop here
803 ulDataTracks = 0;
804 break;
805 }
806 }
807 }
808 }
809
810 // _Pmpf((" got %d audio, %d data tracks",
811 // ulAudioTracks, ulDataTracks));
812
813 if (!ulDataTracks)
814 *pfAudio = TRUE;
815 }
816 else
817 {
818 // not audio disk:
819 // go on then
820 // _Pmpf((" CDROMAUDIO_GETAUDIODISK returned %d", arc));
821 arc = NO_ERROR;
822 }
823 }
824 }
825 else
826 {
827 // not CD-ROM: go on then
828 // _Pmpf((" CDROMDISK_GETDRIVER returned %d", arc));
829 arc = NO_ERROR;
830 }
831
832 return (arc);
833}
834
835/*
836 *@@ doshEnumDrives:
837 * this function enumerates all valid drive letters on
838 * the system by composing a string of drive letters
839 * in the buffer pointed to by pszBuffer, which should
840 * be 27 characters in size to hold information for
841 * all drives. The buffer will be null-terminated.
842 *
843 * If (pcszFileSystem != NULL), only drives matching
844 * the specified file system type (e.g. "HPFS") will
845 * be enumerated. If (pcszFileSystem == NULL), all
846 * drives will be enumerated.
847 *
848 * If (fSkipRemovables == TRUE), removeable drives will
849 * be skipped. This applies to floppy, CD-ROM, and
850 * virtual floppy drives. This will start the search
851 * at drive letter C: so that drives A: and B: will
852 * never be checked (to avoid the hardware bumps).
853 *
854 * Otherwise, the search starts at drive A:. Still,
855 * removeable drives will only be added if valid media
856 * is inserted.
857 *
858 *@@changed V0.9.4 (2000-07-03) [umoeller]: this stopped at the first invalid drive letter; fixed
859 *@@changed V0.9.4 (2000-07-03) [umoeller]: added fSkipRemoveables
860 */
861
862VOID doshEnumDrives(PSZ pszBuffer, // out: drive letters
863 PCSZ pcszFileSystem, // in: FS's to match or NULL
864 BOOL fSkipRemoveables) // in: if TRUE, only non-removeable disks will be returned
865{
866 CHAR szName[5] = "";
867 ULONG ulLogicalDrive = 1, // start with drive A:
868 ulFound = 0; // found drives count
869 APIRET arc = NO_ERROR; // return code
870
871 if (fSkipRemoveables)
872 // start with drive C:
873 ulLogicalDrive = 3;
874
875 // go thru the drives, start with C: (== 3), stop after Z: (== 26)
876 while (ulLogicalDrive <= 26)
877 {
878 #pragma pack(1)
879 struct
880 {
881 UCHAR dummy,drive;
882 } parms;
883 #pragma pack()
884
885 // data packet
886 UCHAR nonRemovable=0;
887
888 parms.drive=(UCHAR)(ulLogicalDrive-1);
889 arc = doshDevIOCtl((HFILE)-1,
890 IOCTL_DISK,
891 DSK_BLOCKREMOVABLE,
892 &parms, sizeof(parms),
893 &nonRemovable, sizeof(nonRemovable));
894
895 if ( // fixed disk and non-removeable
896 ((arc == NO_ERROR) && (nonRemovable))
897 // or network drive:
898 || (arc == ERROR_NOT_SUPPORTED)
899 )
900 {
901 ULONG ulOrdinal = 0; // ordinal of entry in name list
902 BYTE fsqBuffer[sizeof(FSQBUFFER2) + (3 * CCHMAXPATH)] = {0};
903 ULONG cbBuffer = sizeof(fsqBuffer); // Buffer length)
904 PFSQBUFFER2 pfsqBuffer = (PFSQBUFFER2)fsqBuffer;
905
906 szName[0] = ulLogicalDrive + 'A' - 1;
907 szName[1] = ':';
908 szName[2] = '\0';
909
910 arc = DosQueryFSAttach(szName, // logical drive of attached FS
911 ulOrdinal, // ignored for FSAIL_QUERYNAME
912 FSAIL_QUERYNAME, // return data for a Drive or Device
913 pfsqBuffer, // returned data
914 &cbBuffer); // returned data length
915
916 if (arc == NO_ERROR)
917 {
918 // The data for the last three fields in the FSQBUFFER2
919 // structure are stored at the offset of fsqBuffer.szName.
920 // Each data field following fsqBuffer.szName begins
921 // immediately after the previous item.
922 CHAR* pszFSDName = (PSZ)&(pfsqBuffer->szName) + (pfsqBuffer->cbName) + 1;
923 if (pcszFileSystem == NULL)
924 {
925 // enum-all mode: always copy
926 pszBuffer[ulFound] = szName[0]; // drive letter
927 ulFound++;
928 }
929 else if (strcmp(pszFSDName, pcszFileSystem) == 0)
930 {
931 pszBuffer[ulFound] = szName[0]; // drive letter
932 ulFound++;
933 }
934 }
935 }
936
937 ulLogicalDrive++;
938 } // end while (G_acDriveLetters[ulLogicalDrive] <= 'Z')
939
940 pszBuffer[ulFound] = '\0';
941}
942
943/*
944 *@@ doshQueryBootDrive:
945 * returns the letter of the boot drive as a
946 * single (capital) character, which is useful for
947 * constructing file names using sprintf and such.
948 *
949 *@@changed V0.9.16 (2002-01-13) [umoeller]: optimized
950 */
951
952CHAR doshQueryBootDrive(VOID)
953{
954 // this can never change, so query this only once
955 // V0.9.16 (2002-01-13) [umoeller]
956 static CHAR cBootDrive = '\0';
957
958 if (!cBootDrive)
959 {
960 ULONG ulBootDrive;
961 DosQuerySysInfo(QSV_BOOT_DRIVE, QSV_BOOT_DRIVE,
962 &ulBootDrive,
963 sizeof(ulBootDrive));
964 cBootDrive = (CHAR)ulBootDrive + 'A' - 1;
965 }
966
967 return (cBootDrive);
968}
969
970/*
971 *@@ doshQueryMedia:
972 * determines whether the given drive currently
973 * has media inserted.
974 *
975 * Call this only for non-fixed (removable) disks.
976 * Use doshIsFixedDisk to find out.
977 *
978 *@@added V0.9.16 (2002-01-13) [umoeller]
979 */
980
981APIRET doshQueryMedia(ULONG ulLogicalDrive,
982 BOOL fCDROM, // in: is drive CD-ROM?
983 ULONG fl) // in: DRVFL_* flags
984{
985 APIRET arc;
986
987 HFILE hf = NULLHANDLE;
988 ULONG dummy;
989
990 CHAR szDrive[3] = "C:";
991 szDrive[0] = 'A' + ulLogicalDrive - 1;
992
993 arc = DosOpen(szDrive, // "C:", "D:", ...
994 &hf,
995 &dummy,
996 0,
997 FILE_NORMAL,
998 OPEN_ACTION_FAIL_IF_NEW
999 | OPEN_ACTION_OPEN_IF_EXISTS,
1000 OPEN_FLAGS_DASD
1001 | OPEN_FLAGS_FAIL_ON_ERROR
1002 | OPEN_FLAGS_NOINHERIT // V0.9.6 (2000-11-25) [pr]
1003 // | OPEN_ACCESS_READONLY // V0.9.13 (2001-06-14) [umoeller]
1004 | OPEN_SHARE_DENYNONE,
1005 NULL);
1006
1007 // this still returns NO_ERROR for audio CDs in a
1008 // CD-ROM drive...
1009 // however, the WPS then attempts to read in the
1010 // root directory for audio CDs, which produces
1011 // a "sector not found" error box...
1012
1013 if ( (!arc)
1014 && (hf)
1015 && (fCDROM)
1016 )
1017 {
1018 BOOL fAudio;
1019 if ( (!(arc = doshHasAudioCD(ulLogicalDrive,
1020 hf,
1021 ((fl & DRVFL_MIXEDMODECD) != 0),
1022 &fAudio)))
1023 && (fAudio)
1024 )
1025 arc = ERROR_AUDIO_CD_ROM; // special private error code (10000)
1026 }
1027
1028 if (hf)
1029 DosClose(hf);
1030
1031 return (arc);
1032}
1033
1034/*
1035 *@@ doshAssertDrive:
1036 * this checks for whether the given drive
1037 * is currently available without provoking
1038 * those ugly white "Drive not ready" popups.
1039 *
1040 * "fl" can specify additional flags for testing
1041 * and can be any combination of:
1042 *
1043 * -- DRVFL_MIXEDMODECD: whether to allow
1044 * mixed-mode CD-ROMs. See error codes below.
1045 *
1046 * This returns (from my testing):
1047 *
1048 * -- NO_ERROR: drive is available.
1049 *
1050 * -- ERROR_INVALID_DRIVE (15): drive letter does not exist.
1051 *
1052 * -- ERROR_NOT_READY (21): drive exists, but is not ready.
1053 * This is produced by floppies and CD-ROM drives
1054 * which do not have valid media inserted.
1055 *
1056 * -- ERROR_AUDIO_CD_ROM (10000): special error code returned
1057 * only by this function if a CD-ROM drive has audio
1058 * media inserted.
1059 *
1060 * If DRVFL_MIXEDMODECD was specified, ERROR_AUDIO_CD_ROM
1061 * is returned _only_ if _no_ data tracks are
1062 * present on a CD-ROM. Since OS/2 is not very
1063 * good at handling mixed-mode CDs, this might not
1064 * be desireable.
1065 *
1066 * If DRVFL_MIXEDMODECD was not set, ERROR_AUDIO_CD_ROM
1067 * will be returned already if _one_ audio track is present.
1068 *
1069 *@@changed V0.9.1 (99-12-13) [umoeller]: rewritten, prototype changed. Now using DosOpen on the drive instead of DosError.
1070 *@@changed V0.9.1 (2000-01-08) [umoeller]: DosClose was called even if DosOpen failed, which messed up OS/2 error handling.
1071 *@@changed V0.9.1 (2000-02-09) [umoeller]: this didn't work for network drives, including RAMFS; fixed.
1072 *@@changed V0.9.3 (2000-03-28) [umoeller]: added check for network drives, which weren't working
1073 *@@changed V0.9.4 (2000-08-03) [umoeller]: more network fixes
1074 *@@changed V0.9.9 (2001-03-19) [pr]: validate drive number
1075 *@@changed V0.9.11 (2001-04-23) [umoeller]: added an extra check for floppies
1076 *@@changed V0.9.13 (2001-06-14) [umoeller]: added "fl" parameter and lots of CD-ROM checks
1077 */
1078
1079APIRET doshAssertDrive(ULONG ulLogicalDrive, // in: 1 for A:, 2 for B:, 3 for C:, ...
1080 ULONG fl) // in: DRVFL_* flags
1081{
1082 APIRET arc = NO_ERROR;
1083 BOOL fFixed = FALSE,
1084 fCDROM = FALSE;
1085
1086 if ((ulLogicalDrive < 1) || (ulLogicalDrive > 26))
1087 return(ERROR_PATH_NOT_FOUND);
1088
1089 arc = doshIsFixedDisk(ulLogicalDrive,
1090 &fFixed); // V0.9.13 (2001-06-14) [umoeller]
1091
1092 // _Pmpf((__FUNCTION__ ": doshIsFixedDisk returned %d for disk %d", arc, ulLogicalDrive));
1093 // _Pmpf((" fFixed is %d", fFixed));
1094
1095 if (!arc)
1096 if (!fFixed)
1097 {
1098 // removeable disk:
1099 // check if it's a CD-ROM
1100 BIOSPARAMETERBLOCK bpb;
1101 arc = doshQueryDiskParams(ulLogicalDrive,
1102 &bpb);
1103 // _Pmpf((" doshQueryDiskParams returned %d", arc));
1104
1105 if ( (!arc)
1106 && (DRVTYPE_CDROM == doshQueryDriveType(ulLogicalDrive,
1107 &bpb,
1108 fFixed))
1109 )
1110 {
1111 // _Pmpf((" --> is CD-ROM"));
1112 fCDROM = TRUE;
1113 }
1114 }
1115
1116 if (!arc)
1117 arc = doshQueryMedia(ulLogicalDrive,
1118 fCDROM,
1119 fl);
1120
1121 switch (arc)
1122 {
1123 case ERROR_NETWORK_ACCESS_DENIED: // 65
1124 // added V0.9.3 (2000-03-27) [umoeller];
1125 // according to user reports, this is returned
1126 // by all network drives, which apparently don't
1127 // support DASD DosOpen
1128 case ERROR_ACCESS_DENIED: // 5
1129 // added V0.9.4 (2000-07-10) [umoeller]
1130 // LAN drives still didn't work... apparently
1131 // the above only works for NFS drives
1132 case ERROR_PATH_NOT_FOUND: // 3
1133 // added V0.9.4 (2000-08-03) [umoeller]:
1134 // this is returned by some other network types...
1135 // sigh...
1136 case ERROR_NOT_SUPPORTED: // 50
1137 // this is returned by file systems which don't
1138 // support DASD DosOpen;
1139 // use some other method then, this isn't likely
1140 // to fail -- V0.9.1 (2000-02-09) [umoeller]
1141
1142 // but don't do this for floppies
1143 // V0.9.11 (2001-04-23) [umoeller]
1144 if (ulLogicalDrive > 2)
1145 {
1146 FSALLOCATE fsa;
1147 arc = DosQueryFSInfo(ulLogicalDrive,
1148 FSIL_ALLOC,
1149 &fsa,
1150 sizeof(fsa));
1151 // _Pmpf((" re-checked, DosQueryFSInfo returned %d", arc));
1152 }
1153 break;
1154 }
1155
1156 return (arc);
1157}
1158
1159/*
1160 *@@ doshGetDriveInfo:
1161 * fills the given XDISKINFO buffer with
1162 * information about the given logical drive.
1163 *
1164 * This function will not provoke "Drive not
1165 * ready" popups, hopefully.
1166 *
1167 * fl can be any combination of the following:
1168 *
1169 * -- DRVFL_MIXEDMODECD: see doshAssertDrive.
1170 *
1171 * -- DRVFL_TOUCHFLOPPIES: drive A: and B: should
1172 * be touched for media checks (click, click);
1173 * otherwise they will be left alone and
1174 * default values will be returned.
1175 *
1176 * -- DRVFL_CHECKEAS: drive should always be
1177 * checked for EA support. If this is set,
1178 * we will call DosFSCtl for the non-well-known
1179 * file systems so we will always have a
1180 * value for the DFL_SUPPORTS_EAS flags.
1181 * Otherwise that flag might or might not
1182 * be set correctly.
1183 *
1184 * The EA support returned by DosFSCtl
1185 * might not be correct for remote file
1186 * systems since not all of them support
1187 * that query.
1188 *
1189 * -- DRVFL_CHECKLONGNAMES: drive should always be
1190 * checked for longname support. If this is
1191 * set, we will try a DosOpen("\\long.name.file")
1192 * on the drive to see if it supports long
1193 * filenames (unless it's a "well-known"
1194 * file-system and we know it does). If enabled,
1195 * the DFL_SUPPORTS_LONGNAMES flag is reliable.
1196 * Note that this does not check for what special
1197 * characters are supported in file names.
1198 *
1199 * This should return only one of the following:
1200 *
1201 * -- NO_ERROR: disk info was filled, but not
1202 * necessarily all info was available (e.g.
1203 * if no media was present in CD-ROM drive).
1204 * See remarks below.
1205 *
1206 * -- ERROR_INVALID_DRIVE 15): ulLogicalDrive
1207 * is not used at all (invalid drive letter)
1208 *
1209 * -- ERROR_BAD_UNIT (20): if drive was renamed for
1210 * some reason (according to user reports
1211 *
1212 * -- ERROR_NOT_READY (21): for ZIP disks where
1213 * no media is inserted, depending on the
1214 * driver apparently... normally ZIP drive
1215 * letters should disappear when no media
1216 * is present
1217 *
1218 * -- ERROR_DRIVE_LOCKED (108)
1219 *
1220 * So in order to check whether a drive is present
1221 * and available, use this function as follows:
1222 *
1223 * 1) Call this function and check whether it
1224 * returns NO_ERROR for the given drive.
1225 * This will rule out invalid drive letters
1226 * and drives that are presently locked by
1227 * CHKDSK or something.
1228 *
1229 * 2) If so, check whether XDISKINFO.flDevice
1230 * has the DFL_MEDIA_PRESENT flag set.
1231 * This will rule out removeable drives without
1232 * media and unformatted hard disks.
1233 *
1234 * 3) If so, you can test the other fields if
1235 * you need more information. For example,
1236 * it would not be a good idea to create
1237 * a new file if the bType field is
1238 * DRVTYPE_CDROM.
1239 *
1240 * If you want to exclude removeable disks,
1241 * instead of checking bType, you should
1242 * rather check flDevice for the DFL_FIXED
1243 * flag, which will be set for ZIP drives also.
1244 *
1245 * Remarks for special drive types:
1246 *
1247 * -- Hard disks always have bType == DRVTYPE_HARDDISK.
1248 * For them, we always check the file system.
1249 * If this is reported as "UNKNOWN", this means
1250 * that the drive is unformatted or formatted
1251 * with a file system that OS/2 does not understand
1252 * (e.g. NTFS). Only in that case, flDevice
1253 * has the DFL_MEDIA_PRESENT bit clear.
1254 *
1255 * DFL_FIXED is always set.
1256 *
1257 * -- Remote (LAN) drives always have bType == DRVTYPE_LAN.
1258 * flDevice will always have the DFL_REMOTE and
1259 * DFL_MEDIA_PRESENT bits set.
1260 *
1261 * -- ZIP disks will have bType == DRVTYPE_PARTITIONABLEREMOVEABLE.
1262 * For them, flDevice will have both the
1263 * and DFL_PARTITIONABLEREMOVEABLE and DFL_FIXED
1264 * bits set.
1265 *
1266 * ZIP disks are a bit special because they are
1267 * dynamically mounted and unmounted when media
1268 * is inserted and removed. In other words, if
1269 * no media is present, the drive letter becomes
1270 * invalid.
1271 *
1272 * -- CD-ROM and DVD drives and CD writers will always
1273 * be reported as DRVTYPE_CDROM. The DFL_FIXED bit
1274 * will be clear always. For them, always check the
1275 * DFL_MEDIA_PRESENT present bit to avoid "Drive not
1276 * ready" popups.
1277 *
1278 * As a special goody, we can also determine if the
1279 * drive currently has audio media inserted (which
1280 * would provoke errors also), by setting the
1281 * DFL_AUDIO_CD bit.
1282 *
1283 *@@added V0.9.16 (2002-01-13) [umoeller]
1284 */
1285
1286APIRET doshGetDriveInfo(ULONG ulLogicalDrive,
1287 ULONG fl, // in: DRVFL_* flags
1288 PXDISKINFO pdi)
1289{
1290 APIRET arc = NO_ERROR;
1291
1292 HFILE hf;
1293 ULONG dummy;
1294 BOOL fCheck = TRUE,
1295 fCheckFS = FALSE,
1296 fCheckLongnames = FALSE,
1297 fCheckEAs = FALSE;
1298
1299 memset(pdi, 0, sizeof(XDISKINFO));
1300
1301 pdi->cDriveLetter = 'A' + ulLogicalDrive - 1;
1302 pdi->cLogicalDrive = ulLogicalDrive;
1303
1304 pdi->bType = DRVTYPE_UNKNOWN;
1305 pdi->fPresent = TRUE; // for now
1306
1307 if ( (ulLogicalDrive == 1)
1308 || (ulLogicalDrive == 2)
1309 )
1310 {
1311 // drive A: and B: are special cases,
1312 // we don't even want to touch them (click, click)
1313 pdi->bType = DRVTYPE_FLOPPY;
1314
1315 if (0 == (fl & DRVFL_TOUCHFLOPPIES))
1316 {
1317 fCheck = FALSE;
1318 // these support EAs too
1319 pdi->flDevice = DFL_MEDIA_PRESENT | DFL_SUPPORTS_EAS;
1320 strcpy(pdi->szFileSystem, "FAT");
1321 pdi->lFileSystem = FSYS_FAT;
1322 }
1323 }
1324
1325 if (fCheck)
1326 {
1327 // any other drive:
1328 // check if it's removeable first
1329 BOOL fFixed = FALSE;
1330 arc = doshIsFixedDisk(ulLogicalDrive,
1331 &fFixed);
1332
1333 switch (arc)
1334 {
1335 case ERROR_INVALID_DRIVE:
1336 // drive letter doesn't exist at all:
1337 pdi->fPresent = FALSE;
1338 // return this APIRET
1339 break;
1340
1341 case ERROR_NOT_SUPPORTED: // 50 for network drives
1342 // we get this for remote drives added
1343 // via "net use", so set these flags
1344 pdi->bType = DRVTYPE_LAN;
1345 pdi->lFileSystem = FSYS_REMOTE;
1346 pdi->flDevice |= DFL_REMOTE | DFL_MEDIA_PRESENT;
1347 // but still check what file-system we
1348 // have and whether longnames are supported
1349 fCheckFS = TRUE;
1350 fCheckLongnames = TRUE;
1351 fCheckEAs = TRUE;
1352 break;
1353
1354 case NO_ERROR:
1355 {
1356 if (fFixed)
1357 {
1358 // fixed drive:
1359 pdi->flDevice |= DFL_FIXED | DFL_MEDIA_PRESENT;
1360
1361 fCheckFS = TRUE;
1362 fCheckLongnames = TRUE;
1363 fCheckEAs = TRUE;
1364 }
1365
1366 if (!(arc = doshQueryDiskParams(ulLogicalDrive,
1367 &pdi->bpb)))
1368 {
1369 BYTE bTemp = doshQueryDriveType(ulLogicalDrive,
1370 &pdi->bpb,
1371 fFixed);
1372 if (bTemp != DRVTYPE_UNKNOWN)
1373 {
1374 // recognized: store it then
1375 pdi->bType = bTemp;
1376
1377 if (bTemp == DRVTYPE_PARTITIONABLEREMOVEABLE)
1378 pdi->flDevice |= DFL_FIXED
1379 | DFL_PARTITIONABLEREMOVEABLE;
1380 }
1381
1382 if (!fFixed)
1383 {
1384 // removeable:
1385
1386 // before checking the drive, try if we have media
1387 if (!(arc = doshQueryMedia(ulLogicalDrive,
1388 (pdi->bType == DRVTYPE_CDROM),
1389 fl)))
1390 {
1391 pdi->flDevice |= DFL_MEDIA_PRESENT;
1392 fCheckFS = TRUE;
1393 fCheckLongnames = TRUE;
1394 // but never EAs
1395 }
1396 else if (arc == ERROR_AUDIO_CD_ROM)
1397 {
1398 pdi->flDevice |= DFL_AUDIO_CD;
1399 // do not check longnames and file-system
1400 }
1401 else
1402 pdi->arcQueryMedia = arc;
1403
1404 arc = NO_ERROR;
1405 }
1406 }
1407 else
1408 pdi->arcQueryDiskParams = arc;
1409 }
1410 break;
1411
1412 default:
1413 pdi->arcIsFixedDisk = arc;
1414 // and return this
1415 break;
1416
1417 } // end swich arc = doshIsFixedDisk(ulLogicalDrive, &fFixed);
1418 }
1419
1420 if (fCheckFS)
1421 {
1422 // TRUE only for local fixed disks or
1423 // remote drives or if media was present above
1424 if (!(arc = doshQueryDiskFSType(ulLogicalDrive,
1425 pdi->szFileSystem,
1426 sizeof(pdi->szFileSystem))))
1427 {
1428 if (!stricmp(pdi->szFileSystem, "UNKNOWN"))
1429 {
1430 // this is returned by the stupid DosQueryFSAttach
1431 // if the file system is not recognized by OS/2,
1432 // or if the drive is unformatted
1433 pdi->lFileSystem = FSYS_UNKNOWN;
1434 pdi->flDevice &= ~DFL_MEDIA_PRESENT;
1435 fCheckLongnames = FALSE;
1436 fCheckEAs = FALSE;
1437 // should we return ERROR_NOT_DOS_DISK (26)
1438 // in this case?
1439 }
1440 else if (!stricmp(pdi->szFileSystem, "FAT"))
1441 {
1442 pdi->lFileSystem = FSYS_FAT;
1443 pdi->flDevice |= DFL_SUPPORTS_EAS;
1444 fCheckLongnames = FALSE;
1445 fCheckEAs = FALSE;
1446 }
1447 else if ( (!stricmp(pdi->szFileSystem, "HPFS"))
1448 || (!stricmp(pdi->szFileSystem, "JFS"))
1449 )
1450 {
1451 pdi->lFileSystem = FSYS_HPFS_JFS;
1452 pdi->flDevice |= DFL_SUPPORTS_EAS | DFL_SUPPORTS_LONGNAMES;
1453 fCheckLongnames = FALSE;
1454 fCheckEAs = FALSE;
1455 }
1456 else if (!stricmp(pdi->szFileSystem, "CDFS"))
1457 pdi->lFileSystem = FSYS_CDFS;
1458 else if ( (!stricmp(pdi->szFileSystem, "FAT32"))
1459 || (!stricmp(pdi->szFileSystem, "ext2"))
1460 )
1461 {
1462 pdi->lFileSystem = FSYS_FAT32_EXT2;
1463 fCheckLongnames = TRUE;
1464 fCheckEAs = TRUE;
1465 }
1466 else if (!stricmp(pdi->szFileSystem, "RAMFS"))
1467 {
1468 pdi->lFileSystem = FSYS_RAMFS;
1469 pdi->flDevice |= DFL_SUPPORTS_EAS | DFL_SUPPORTS_LONGNAMES;
1470 fCheckLongnames = FALSE;
1471 fCheckEAs = FALSE;
1472 }
1473 else if (!stricmp(pdi->szFileSystem, "TVFS"))
1474 {
1475 pdi->lFileSystem = FSYS_TVFS;
1476 fCheckLongnames = TRUE;
1477 fCheckEAs = TRUE;
1478 }
1479 }
1480 else
1481 // store negative error code
1482 pdi->lFileSystem = -(LONG)arc;
1483 }
1484
1485 if ( (!arc)
1486 && (fCheckLongnames)
1487 && (fl & DRVFL_CHECKLONGNAMES)
1488 )
1489 {
1490 CHAR szTemp[30] = "?:\\long.name.file";
1491 szTemp[0] = ulLogicalDrive + 'A' - 1;
1492 if (!(arc = DosOpen(szTemp,
1493 &hf,
1494 &dummy,
1495 0,
1496 0,
1497 FILE_READONLY,
1498 OPEN_SHARE_DENYNONE | OPEN_FLAGS_NOINHERIT,
1499 0)))
1500 {
1501 DosClose(hf);
1502 }
1503
1504 switch (arc)
1505 {
1506 case NO_ERROR:
1507 case ERROR_OPEN_FAILED:
1508 case ERROR_FILE_NOT_FOUND: // returned by TVFS
1509 pdi->flDevice |= DFL_SUPPORTS_LONGNAMES;
1510 break;
1511
1512 // if longnames are not supported,
1513 // we get ERROR_INVALID_NAME
1514 default:
1515 pdi->arcOpenLongnames = arc;
1516 break;
1517
1518 // default:
1519 // printf(" drive %d returned %d\n", ulLogicalDrive, arc);
1520 }
1521
1522 arc = NO_ERROR;
1523 }
1524
1525 if ( (!arc)
1526 && (fCheckEAs)
1527 && (fl & DRVFL_CHECKEAS)
1528 )
1529 {
1530 EASIZEBUF easb = {0};
1531 ULONG cbData = sizeof(easb),
1532 cbParams = 0;
1533 CHAR szDrive[] = "?:\\";
1534 szDrive[0] = pdi->cDriveLetter;
1535 if (!(arc = DosFSCtl(&easb,
1536 cbData,
1537 &cbData,
1538 NULL, // params,
1539 cbParams,
1540 &cbParams,
1541 FSCTL_MAX_EASIZE,
1542 szDrive,
1543 -1, // HFILE
1544 FSCTL_PATHNAME)))
1545 if (easb.cbMaxEASize != 0)
1546 // the other field (cbMaxEAListSize) is 0 always, I think
1547 pdi->flDevice |= DFL_SUPPORTS_EAS;
1548 }
1549
1550 if (doshQueryBootDrive() == pdi->cDriveLetter)
1551 pdi->flDevice |= DFL_BOOTDRIVE;
1552
1553 return (arc);
1554}
1555
1556/*
1557 *@@ doshSetLogicalMap:
1558 * sets the mapping of logical floppy drives onto a single
1559 * physical floppy drive.
1560 * This means selecting either drive A: or drive B: to refer
1561 * to the physical drive.
1562 *
1563 *@@added V0.9.6 (2000-11-24) [pr]
1564 */
1565
1566APIRET doshSetLogicalMap(ULONG ulLogicalDrive)
1567{
1568 CHAR name[3] = "?:";
1569 ULONG fd = 0,
1570 action = 0;
1571// paramsize = 0;
1572// datasize = 0;
1573 APIRET rc = NO_ERROR;
1574 USHORT data,
1575 param;
1576
1577 name[0] = doshQueryBootDrive();
1578 rc = DosOpen(name,
1579 &fd,
1580 &action,
1581 0,
1582 0,
1583 OPEN_ACTION_FAIL_IF_NEW
1584 | OPEN_ACTION_OPEN_IF_EXISTS,
1585 OPEN_FLAGS_DASD
1586 | OPEN_FLAGS_FAIL_ON_ERROR
1587 | OPEN_FLAGS_NOINHERIT
1588 | OPEN_ACCESS_READONLY
1589 | OPEN_SHARE_DENYNONE,
1590 0);
1591
1592 if (rc == NO_ERROR)
1593 {
1594 param = 0;
1595 data = (USHORT)ulLogicalDrive;
1596 // paramsize = sizeof(param);
1597 // datasize = sizeof(data);
1598 rc = doshDevIOCtl(fd,
1599 IOCTL_DISK, DSK_SETLOGICALMAP,
1600 &param, sizeof(param),
1601 &data, sizeof(data));
1602 DosClose(fd);
1603 }
1604
1605 return(rc);
1606}
1607
1608/*
1609 *@@ doshQueryDiskSize:
1610 * returns the size of the specified disk in bytes.
1611 *
1612 * Note: This returns a "double" value, because a ULONG
1613 * can only hold values of some 4 billion, which would
1614 * lead to funny results for drives > 4 GB.
1615 *
1616 *@@added V0.9.11 (2001-04-18) [umoeller]
1617 */
1618
1619APIRET doshQueryDiskSize(ULONG ulLogicalDrive, // in: 1 for A:, 2 for B:, 3 for C:, ...
1620 double *pdSize)
1621{
1622 APIRET arc = NO_ERROR;
1623 FSALLOCATE fsa;
1624 // double dbl = -1;
1625
1626 if (!(arc = DosQueryFSInfo(ulLogicalDrive, FSIL_ALLOC, &fsa, sizeof(fsa))))
1627 *pdSize = ((double)fsa.cSectorUnit * fsa.cbSector * fsa.cUnit);
1628
1629 return (arc);
1630}
1631
1632/*
1633 *@@ doshQueryDiskFree:
1634 * returns the number of bytes remaining on the disk
1635 * specified by the given logical drive.
1636 *
1637 * Note: This returns a "double" value, because a ULONG
1638 * can only hold values of some 4 billion, which would
1639 * lead to funny results for drives > 4 GB.
1640 *
1641 *@@changed V0.9.0 [umoeller]: fixed another > 4 GB bug (thanks to Rdiger Ihle)
1642 *@@changed V0.9.7 (2000-12-01) [umoeller]: changed prototype
1643 */
1644
1645APIRET doshQueryDiskFree(ULONG ulLogicalDrive, // in: 1 for A:, 2 for B:, 3 for C:, ...
1646 double *pdFree)
1647{
1648 APIRET arc = NO_ERROR;
1649 FSALLOCATE fsa;
1650 // double dbl = -1;
1651
1652 if (!(arc = DosQueryFSInfo(ulLogicalDrive, FSIL_ALLOC, &fsa, sizeof(fsa))))
1653 *pdFree = ((double)fsa.cSectorUnit * fsa.cbSector * fsa.cUnitAvail);
1654 // ^ fixed V0.9.0
1655
1656 return (arc);
1657}
1658
1659/*
1660 *@@ doshQueryDiskFSType:
1661 * copies the file-system type of the given disk object
1662 * (HPFS, FAT, CDFS etc.) to pszBuf.
1663 * Returns the DOS error code.
1664 *
1665 *@@changed V0.9.1 (99-12-12) [umoeller]: added cbBuf to prototype
1666 *@@changed V0.9.14 (2001-08-01) [umoeller]: fixed, this never respected cbBuf
1667 *@@changed V0.9.16 (2001-10-02) [umoeller]: added check for valid logical disk no
1668 */
1669
1670APIRET doshQueryDiskFSType(ULONG ulLogicalDrive, // in: 1 for A:, 2 for B:, 3 for C:, ...
1671 PSZ pszBuf, // out: buffer for FS type
1672 ULONG cbBuf) // in: size of that buffer
1673{
1674 APIRET arc = NO_ERROR;
1675 CHAR szName[5];
1676
1677 BYTE fsqBuffer[sizeof(FSQBUFFER2) + (3 * CCHMAXPATH)] = {0};
1678 ULONG cbBuffer = sizeof(fsqBuffer); // Buffer length)
1679 PFSQBUFFER2 pfsqBuffer = (PFSQBUFFER2)fsqBuffer;
1680
1681 // compose "D:"-type string from logical drive letter
1682 if (ulLogicalDrive > 0 && ulLogicalDrive < 27)
1683 {
1684 szName[0] = ulLogicalDrive + 'A' - 1;
1685 szName[1] = ':';
1686 szName[2] = '\0';
1687
1688 arc = DosQueryFSAttach(szName, // logical drive of attached FS ("D:"-style)
1689 0, // ulOrdinal, ignored for FSAIL_QUERYNAME
1690 FSAIL_QUERYNAME, // return name for a drive or device
1691 pfsqBuffer, // buffer for returned data
1692 &cbBuffer); // sizeof(*pfsqBuffer)
1693
1694 if (arc == NO_ERROR)
1695 {
1696 if (pszBuf)
1697 {
1698 // The data for the last three fields in the FSQBUFFER2
1699 // structure are stored at the offset of fsqBuffer.szName.
1700 // Each data field following fsqBuffer.szName begins
1701 // immediately after the previous item.
1702 strncpy(pszBuf,
1703 (CHAR*)(&pfsqBuffer->szName) + pfsqBuffer->cbName + 1,
1704 cbBuf); // V0.9.14 (2001-08-01) [umoeller]
1705 *(pszBuf + cbBuf) = '\0';
1706 }
1707 }
1708 }
1709 else
1710 arc = ERROR_INVALID_PARAMETER; // V0.9.16 (2001-10-02) [umoeller]
1711
1712 return (arc);
1713}
1714
1715/*
1716 *@@ doshQueryDiskLabel:
1717 * this returns the label of a disk into
1718 * *pszVolumeLabel, which must be 12 bytes
1719 * in size.
1720 *
1721 * This function was added because the Toolkit
1722 * information for DosQueryFSInfo is only partly
1723 * correct. On OS/2 2.x, that function does not
1724 * take an FSINFO structure as input, but a VOLUMELABEL.
1725 * On Warp, this does take an FSINFO.
1726 *
1727 * DosSetFSInfo is even worse. See doshSetDiskLabel.
1728 *
1729 * See http://zebra.asta.fh-weingarten.de/os2/Snippets/Bugi6787.HTML
1730 * for details.
1731 *
1732 *@@added V0.9.0 [umoeller]
1733 *@@changed V0.9.11 (2001-04-22) [umoeller]: this copied even with errors, fixed
1734 */
1735
1736APIRET doshQueryDiskLabel(ULONG ulLogicalDrive, // in: 1 for A:, 2 for B:, 3 for C:, ...
1737 PSZ pszVolumeLabel) // out: volume label (must be 12 chars in size)
1738{
1739 APIRET arc;
1740
1741 #ifdef __OS2V2X__
1742 VOLUMELABEL FSInfoBuf;
1743 #else
1744 FSINFO FSInfoBuf;
1745 #endif
1746
1747 arc = DosQueryFSInfo(ulLogicalDrive,
1748 FSIL_VOLSER,
1749 &FSInfoBuf,
1750 sizeof(FSInfoBuf)); // depends
1751
1752 if (!arc) // V0.9.11 (2001-04-22) [umoeller]
1753 {
1754 #ifdef __OS2V2X__
1755 strcpy(pszVolumeLabel, FSInfoBuf.szVolLabel);
1756 #else
1757 strcpy(pszVolumeLabel, FSInfoBuf.vol.szVolLabel);
1758 #endif
1759 }
1760
1761 return (arc);
1762}
1763
1764/*
1765 *@@ doshSetDiskLabel:
1766 * this sets the label of a disk.
1767 *
1768 * This function was added because the Toolkit
1769 * information for DosSetFSInfo is flat out wrong.
1770 * That function does not take an FSINFO structure
1771 * as input, but a VOLUMELABEL. As a result, using
1772 * that function with the Toolkit's calling specs
1773 * results in ERROR_LABEL_TOO_LONG always.
1774 *
1775 * See http://zebra.asta.fh-weingarten.de/os2/Snippets/Bugi6787.HTML
1776 * for details.
1777 *
1778 *@@added V0.9.0 [umoeller]
1779 */
1780
1781APIRET doshSetDiskLabel(ULONG ulLogicalDrive, // in: 1 for A:, 2 for B:, 3 for C:, ...
1782 PSZ pszNewLabel)
1783{
1784 VOLUMELABEL FSInfoBuf;
1785
1786 // check length; 11 chars plus null byte allowed
1787 FSInfoBuf.cch = (BYTE)strlen(pszNewLabel);
1788 if (FSInfoBuf.cch < sizeof(FSInfoBuf.szVolLabel))
1789 {
1790 strcpy(FSInfoBuf.szVolLabel, pszNewLabel);
1791
1792 return (DosSetFSInfo(ulLogicalDrive,
1793 FSIL_VOLSER,
1794 &FSInfoBuf,
1795 sizeof(FSInfoBuf)));
1796 }
1797 else
1798 return (ERROR_LABEL_TOO_LONG);
1799}
1800
1801/*
1802 *@@category: Helpers\Control program helpers\File name parsing
1803 */
1804
1805/* ******************************************************************
1806 *
1807 * File name parsing
1808 *
1809 ********************************************************************/
1810
1811/*
1812 *@@ doshGetDriveSpec:
1813 * returns the drive specification in pcszFullFile,
1814 * if any is present. This is useful for UNC support.
1815 *
1816 * This returns:
1817 *
1818 * -- NO_ERROR: drive spec was given, and the output
1819 * fields have been set.
1820 *
1821 * -- ERROR_INVALID_NAME: incorrect UNC syntax.
1822 *
1823 * -- ERROR_INVALID_DRIVE: second char is ':', but
1824 * drive letter is not in the range [A-Z].
1825 *
1826 * -- ERROR_INVALID_PARAMETER: no drive spec given
1827 * at all; apparently pcszFullFile is not fully
1828 * qualified in the first place, or it is NULL,
1829 * or its length is <= 2.
1830 *
1831 *@@added V0.9.16 (2001-10-25) [umoeller]
1832 */
1833
1834APIRET doshGetDriveSpec(PCSZ pcszFullFile, // in: fully q'fied file spec
1835 PSZ pszDrive, // out: drive spec ("C:" or "\\SERVER\RESOURCE"; ptr can be NULL)
1836 PULONG pulDriveLen, // out: length of drive spec (2 if local drive; ptr can be NULL)
1837 PBOOL pfIsUNC) // out: set to TRUE if UNC name, FALSE otherwise (ptr can be NULL)
1838{
1839 APIRET arc = NO_ERROR;
1840 ULONG ulFileSpecLength;
1841
1842 if ( (pcszFullFile)
1843 && (ulFileSpecLength = strlen(pcszFullFile))
1844 && (ulFileSpecLength >= 2)
1845 )
1846 {
1847 // upper-case the drive letter
1848 if (pcszFullFile[1] == ':')
1849 {
1850 CHAR cDrive = toupper(*pcszFullFile);
1851 // local drive specified:
1852 if ( (cDrive >= 'A')
1853 && (cDrive <= 'Z')
1854 )
1855 {
1856 if (pszDrive)
1857 {
1858 pszDrive[0] = cDrive;
1859 pszDrive[1] = ':';
1860 pszDrive[2] = '\0';
1861 }
1862
1863 if (pulDriveLen)
1864 *pulDriveLen = 2;
1865 if (pfIsUNC)
1866 *pfIsUNC = FALSE;
1867 }
1868 else
1869 // this is not a valid drive:
1870 arc = ERROR_INVALID_DRIVE;
1871 }
1872 else if ( (pcszFullFile[0] == '\\')
1873 && (pcszFullFile[1] == '\\')
1874 )
1875 {
1876 // UNC drive specified:
1877 // this better be a full \\SERVER\RESOURCE string
1878 PCSZ pResource;
1879 if (pResource = strchr(pcszFullFile + 3, '\\'))
1880 {
1881 // we got at least \\SERVER\:
1882 ULONG ulLength;
1883 PCSZ p;
1884
1885 // check if more stuff is coming
1886 if (p = strchr(pResource + 1, '\\'))
1887 {
1888 // yes: copy server and resource excluding that backslash
1889 if (p == pResource + 1)
1890 // "\\SERVER\\" is invalid
1891 arc = ERROR_INVALID_NAME;
1892 else
1893 // we got "\\SERVER\something\":
1894 // drop the last backslash
1895 ulLength = p - pcszFullFile;
1896 }
1897 else
1898 // "\\SERVER\something" only:
1899 ulLength = ulFileSpecLength;
1900
1901 if (!arc)
1902 {
1903 if (pszDrive)
1904 {
1905 memcpy(pszDrive,
1906 pcszFullFile,
1907 ulLength);
1908 pszDrive[ulLength] = '\0';
1909 }
1910
1911 if (pulDriveLen)
1912 *pulDriveLen = ulLength;
1913 if (pfIsUNC)
1914 *pfIsUNC = TRUE;
1915 }
1916 }
1917 else
1918 // invalid UNC name:
1919 arc = ERROR_INVALID_NAME;
1920 }
1921 else
1922 // neither local, nor UNC:
1923 arc = ERROR_INVALID_PARAMETER;
1924 }
1925 else
1926 arc = ERROR_INVALID_PARAMETER;
1927
1928 return (arc);
1929}
1930
1931/*
1932 *@@ doshGetExtension:
1933 * finds the file name extension of pszFilename,
1934 * which can be a file name only or a fully
1935 * qualified filename.
1936 *
1937 * This returns a pointer into pszFilename to
1938 * the character after the last dot.
1939 *
1940 * Returns NULL if not found (e.g. if the filename
1941 * has no dot in it).
1942 *
1943 * In the pathological case of a dot in the path
1944 * but not in the filename itself, this correctly
1945 * returns NULL.
1946 *
1947 *@@added V0.9.6 (2000-10-16) [umoeller]
1948 *@@changed V0.9.7 (2000-12-10) [umoeller]: fixed "F:filename.ext" case
1949 */
1950
1951PSZ doshGetExtension(PCSZ pcszFilename)
1952{
1953 PSZ pReturn = NULL;
1954
1955 if (pcszFilename)
1956 {
1957 // find filename
1958 PCSZ p2,
1959 pStartOfName = NULL,
1960 pExtension = NULL;
1961
1962 if (p2 = strrchr(pcszFilename + 2, '\\'))
1963 // works on "C:\blah" or "\\unc\blah"
1964 pStartOfName = p2 + 1;
1965 else
1966 {
1967 // no backslash found:
1968 // maybe only a drive letter was specified:
1969 if (pcszFilename[1] == ':')
1970 // yes:
1971 pStartOfName = pcszFilename + 2;
1972 else
1973 // then this is not qualified at all...
1974 // use start of filename
1975 pStartOfName = (PSZ)pcszFilename;
1976 }
1977
1978 // find last dot in filename
1979 if (pExtension = strrchr(pStartOfName, '.'))
1980 pReturn = (PSZ)pExtension + 1;
1981 }
1982
1983 return (pReturn);
1984}
1985
1986/*
1987 *@@category: Helpers\Control program helpers\File management
1988 */
1989
1990/* ******************************************************************
1991 *
1992 * File helpers
1993 *
1994 ********************************************************************/
1995
1996/*
1997 *@@ doshIsFileOnFAT:
1998 * returns TRUE if pszFileName resides on
1999 * a FAT drive. Note that pszFileName must
2000 * be fully qualified (i.e. the drive letter
2001 * must be the first character), or this will
2002 * return garbage.
2003 */
2004
2005BOOL doshIsFileOnFAT(const char* pcszFileName)
2006{
2007 BOOL brc = FALSE;
2008 CHAR szName[5];
2009
2010 APIRET rc = NO_ERROR; // return code
2011 BYTE fsqBuffer[sizeof(FSQBUFFER2) + (3 * CCHMAXPATH)] = {0};
2012 ULONG cbBuffer = sizeof(fsqBuffer); // Buffer length)
2013 PFSQBUFFER2 pfsqBuffer = (PFSQBUFFER2)fsqBuffer;
2014
2015 szName[0] = pcszFileName[0]; // copy drive letter
2016 szName[1] = ':';
2017 szName[2] = '\0';
2018
2019 rc = DosQueryFSAttach(szName, // logical drive of attached FS
2020 0, // ulOrdinal, ignored for FSAIL_QUERYNAME
2021 FSAIL_QUERYNAME, // return data for a Drive or Device
2022 pfsqBuffer, // returned data
2023 &cbBuffer); // returned data length
2024
2025 if (rc == NO_ERROR)
2026 {
2027 // The data for the last three fields in the FSQBUFFER2
2028 // structure are stored at the offset of fsqBuffer.szName.
2029 // Each data field following fsqBuffer.szName begins
2030 // immediately after the previous item.
2031 if (!strncmp((PSZ)&(pfsqBuffer->szName) + pfsqBuffer->cbName + 1,
2032 "FAT",
2033 3))
2034 brc = TRUE;
2035 }
2036
2037 return (brc);
2038}
2039
2040/*
2041 *@@ doshQueryFileSize:
2042 * returns the size of an already opened file
2043 * or 0 upon errors.
2044 * Use doshQueryPathSize to query the size of
2045 * any file.
2046 *
2047 *@@changed V0.9.16 (2001-10-19) [umoeller]: now returning APIRET
2048 */
2049
2050APIRET doshQueryFileSize(HFILE hFile, // in: file handle
2051 PULONG pulSize) // out: file size (ptr can be NULL)
2052{
2053 APIRET arc;
2054 FILESTATUS3 fs3;
2055 if (!(arc = DosQueryFileInfo(hFile, FIL_STANDARD, &fs3, sizeof(fs3))))
2056 if (pulSize)
2057 *pulSize = fs3.cbFile;
2058 return (arc);
2059}
2060
2061/*
2062 *@@ doshQueryPathSize:
2063 * returns the size of any file,
2064 * or 0 if the file could not be
2065 * found.
2066 *
2067 * Use doshQueryFileSize instead to query the
2068 * size if you have a HFILE.
2069 *
2070 * Otherwise this returns:
2071 *
2072 * -- ERROR_FILE_NOT_FOUND
2073 * -- ERROR_PATH_NOT_FOUND
2074 * -- ERROR_SHARING_VIOLATION
2075 * -- ERROR_FILENAME_EXCED_RANGE
2076 * -- ERROR_INVALID_PARAMETER
2077 *
2078 *@@changed V0.9.16 (2001-10-19) [umoeller]: now returning APIRET
2079 */
2080
2081APIRET doshQueryPathSize(PCSZ pcszFile, // in: filename
2082 PULONG pulSize) // out: file size (ptr can be NULL)
2083{
2084 APIRET arc;
2085
2086 if (pcszFile) // V0.9.16 (2001-12-08) [umoeller]
2087 {
2088 FILESTATUS3 fs3;
2089 if (!(arc = DosQueryPathInfo((PSZ)pcszFile, FIL_STANDARD, &fs3, sizeof(fs3))))
2090 if (pulSize)
2091 *pulSize = fs3.cbFile;
2092 }
2093 else
2094 arc = ERROR_INVALID_PARAMETER;
2095
2096 return (arc);
2097}
2098
2099/*
2100 *@@ doshQueryPathAttr:
2101 * returns the file attributes of pszFile,
2102 * which can be fully qualified. The
2103 * attributes will be stored in *pulAttr.
2104 * pszFile can also specify a directory,
2105 * although not all attributes make sense
2106 * for directories.
2107 *
2108 * fAttr can be:
2109 * -- FILE_ARCHIVED
2110 * -- FILE_READONLY
2111 * -- FILE_SYSTEM
2112 * -- FILE_HIDDEN
2113 *
2114 * This returns the APIRET of DosQueryPathInfo.
2115 * *pulAttr is only valid if NO_ERROR is
2116 * returned.
2117 *
2118 * Otherwise this returns:
2119 *
2120 * -- ERROR_FILE_NOT_FOUND
2121 * -- ERROR_PATH_NOT_FOUND
2122 * -- ERROR_SHARING_VIOLATION
2123 * -- ERROR_FILENAME_EXCED_RANGE
2124 *
2125 *@@added V0.9.0 [umoeller]
2126 */
2127
2128APIRET doshQueryPathAttr(const char* pcszFile, // in: file or directory name
2129 PULONG pulAttr) // out: attributes (ptr can be NULL)
2130{
2131 FILESTATUS3 fs3;
2132 APIRET arc;
2133
2134 if (!(arc = DosQueryPathInfo((PSZ)pcszFile,
2135 FIL_STANDARD,
2136 &fs3,
2137 sizeof(fs3))))
2138 {
2139 if (pulAttr)
2140 *pulAttr = fs3.attrFile;
2141 }
2142
2143 return (arc);
2144}
2145
2146/*
2147 *@@ doshSetPathAttr:
2148 * sets the file attributes of pszFile,
2149 * which can be fully qualified.
2150 * pszFile can also specify a directory,
2151 * although not all attributes make sense
2152 * for directories.
2153 *
2154 * fAttr can be:
2155 * -- FILE_ARCHIVED
2156 * -- FILE_READONLY
2157 * -- FILE_SYSTEM
2158 * -- FILE_HIDDEN
2159 *
2160 * Note that this simply sets all the given
2161 * attributes; the existing attributes
2162 * are lost.
2163 *
2164 * This returns the APIRET of DosQueryPathInfo.
2165 */
2166
2167APIRET doshSetPathAttr(const char* pcszFile, // in: file or directory name
2168 ULONG ulAttr) // in: new attributes
2169{
2170 APIRET arc;
2171
2172 if (pcszFile)
2173 {
2174 FILESTATUS3 fs3;
2175 if (!(arc = DosQueryPathInfo((PSZ)pcszFile,
2176 FIL_STANDARD,
2177 &fs3,
2178 sizeof(fs3))))
2179 {
2180 fs3.attrFile = ulAttr;
2181 arc = DosSetPathInfo((PSZ)pcszFile,
2182 FIL_STANDARD,
2183 &fs3,
2184 sizeof(fs3),
2185 DSPI_WRTTHRU);
2186 }
2187 }
2188 else
2189 arc = ERROR_INVALID_PARAMETER;
2190
2191 return (arc);
2192}
2193
2194/*
2195 *@@category: Helpers\Control program helpers\File management\XFILEs
2196 */
2197
2198/* ******************************************************************
2199 *
2200 * XFILEs
2201 *
2202 ********************************************************************/
2203
2204/*
2205 * doshOpen:
2206 * wrapper around DosOpen for simpler opening
2207 * of files.
2208 *
2209 * ulOpenMode determines the mode to open the
2210 * file in (fptr specifies the position after
2211 * the open):
2212 *
2213 + +-------------------------+------+------------+-----------+
2214 + | ulOpenMode | mode | if exists | if new |
2215 + +-------------------------+------+------------+-----------+
2216 + | XOPEN_READ_EXISTING | read | opens | fails |
2217 + | | | fptr = 0 | |
2218 + +-------------------------+------+------------+-----------+
2219 + | XOPEN_READWRITE_EXISTING r/w | opens | fails |
2220 + | | | fptr = 0 | |
2221 + +-------------------------+------+------------+-----------+
2222 + | XOPEN_READWRITE_APPEND | r/w | opens, | creates |
2223 + | | | appends | |
2224 + | | | fptr = end | fptr = 0 |
2225 + +-------------------------+------+------------+-----------+
2226 + | XOPEN_READWRITE_NEW | r/w | replaces | creates |
2227 + | | | fptr = 0 | fptr = 0 |
2228 + +-------------------------+------+------------+-----------+
2229 *
2230 * In addition, you can OR one of the above values with
2231 * the XOPEN_BINARY flag:
2232 *
2233 * -- If XOPEN_BINARY is set, no conversion is performed
2234 * on read and write.
2235 *
2236 * -- If XOPEN_BINARY is _not_ set, all \n chars are
2237 * converted to \r\n on write.
2238 *
2239 * *ppFile receives a new XFILE structure describing
2240 * the open file, if NO_ERROR is returned.
2241 *
2242 * The file pointer is then set to the beginning of the
2243 * file _unless_ XOPEN_READWRITE_APPEND was specified;
2244 * in that case only, the file pointer is set to the
2245 * end of the file so data can be appended (see above).
2246 *
2247 * Otherwise this returns:
2248 *
2249 * -- ERROR_FILE_NOT_FOUND
2250 * -- ERROR_PATH_NOT_FOUND
2251 * -- ERROR_SHARING_VIOLATION
2252 * -- ERROR_FILENAME_EXCED_RANGE
2253 *
2254 * -- ERROR_NOT_ENOUGH_MEMORY
2255 * -- ERROR_INVALID_PARAMETER
2256 *
2257 *@@added V0.9.16 (2001-10-19) [umoeller]
2258 *@@changed V0.9.16 (2001-12-18) [umoeller]: fixed error codes
2259 */
2260
2261APIRET doshOpen(PCSZ pcszFilename, // in: filename to open
2262 ULONG flOpenMode, // in: XOPEN_* mode
2263 PULONG pcbFile, // in: new file size (if new file is created)
2264 // out: file size
2265 PXFILE *ppFile)
2266{
2267 APIRET arc = NO_ERROR;
2268
2269 ULONG fsOpenFlags = 0,
2270 fsOpenMode = OPEN_FLAGS_FAIL_ON_ERROR
2271 | OPEN_FLAGS_NO_LOCALITY
2272 | OPEN_FLAGS_NOINHERIT;
2273
2274 switch (flOpenMode & XOPEN_ACCESS_MASK)
2275 {
2276 case XOPEN_READ_EXISTING:
2277 fsOpenFlags = OPEN_ACTION_FAIL_IF_NEW
2278 | OPEN_ACTION_OPEN_IF_EXISTS;
2279 fsOpenMode |= OPEN_SHARE_DENYWRITE
2280 | OPEN_ACCESS_READONLY;
2281
2282 // run this first, because if the file doesn't
2283 // exists, DosOpen only returns ERROR_OPEN_FAILED,
2284 // which isn't that meaningful
2285 // V0.9.16 (2001-12-08) [umoeller]
2286 arc = doshQueryPathSize(pcszFilename,
2287 pcbFile);
2288 break;
2289
2290 case XOPEN_READWRITE_EXISTING:
2291 fsOpenFlags = OPEN_ACTION_FAIL_IF_NEW
2292 | OPEN_ACTION_OPEN_IF_EXISTS;
2293 fsOpenMode |= OPEN_SHARE_DENYWRITE
2294 | OPEN_ACCESS_READWRITE;
2295
2296 arc = doshQueryPathSize(pcszFilename,
2297 pcbFile);
2298 break;
2299
2300 case XOPEN_READWRITE_APPEND:
2301 fsOpenFlags = OPEN_ACTION_CREATE_IF_NEW
2302 | OPEN_ACTION_OPEN_IF_EXISTS;
2303 fsOpenMode |= OPEN_SHARE_DENYREADWRITE
2304 | OPEN_ACCESS_READWRITE;
2305 // _Pmpf((__FUNCTION__ ": opening XOPEN_READWRITE_APPEND"));
2306 break;
2307
2308 case XOPEN_READWRITE_NEW:
2309 fsOpenFlags = OPEN_ACTION_CREATE_IF_NEW
2310 | OPEN_ACTION_REPLACE_IF_EXISTS;
2311 fsOpenMode |= OPEN_SHARE_DENYREADWRITE
2312 | OPEN_ACCESS_READWRITE;
2313 // _Pmpf((__FUNCTION__ ": opening XOPEN_READWRITE_NEW"));
2314 break;
2315 }
2316
2317 if ((!arc) && fsOpenFlags && pcbFile && ppFile)
2318 {
2319 PXFILE pFile;
2320 if (pFile = NEW(XFILE))
2321 {
2322 ULONG ulAction;
2323
2324 ZERO(pFile);
2325
2326 // copy open flags
2327 pFile->flOpenMode = flOpenMode;
2328
2329 if (!(arc = DosOpen((PSZ)pcszFilename,
2330 &pFile->hf,
2331 &ulAction,
2332 *pcbFile,
2333 FILE_ARCHIVED,
2334 fsOpenFlags,
2335 fsOpenMode,
2336 NULL))) // EAs
2337 {
2338 // alright, got the file:
2339
2340 if ( (ulAction == FILE_EXISTED)
2341 && ((flOpenMode & XOPEN_ACCESS_MASK) == XOPEN_READWRITE_APPEND)
2342 )
2343 // get its size and set ptr to end for append
2344 arc = DosSetFilePtr(pFile->hf,
2345 0,
2346 FILE_END,
2347 pcbFile);
2348 else
2349 arc = doshQueryFileSize(pFile->hf,
2350 pcbFile);
2351 // file ptr is at beginning
2352
2353 #ifdef DEBUG_DOSOPEN
2354 if (arc)
2355 _Pmpf((__FUNCTION__ ": DosSetFilePtr/queryfilesize returned %d for %s",
2356 arc, pcszFilename));
2357 #endif
2358
2359 // store file size
2360 pFile->cbInitial
2361 = pFile->cbCurrent
2362 = *pcbFile;
2363
2364 pFile->pszFilename = strdup(pcszFilename);
2365 }
2366 #ifdef DEBUG_DOSOPEN
2367 else
2368 _Pmpf((__FUNCTION__ ": DosOpen returned %d for %s",
2369 arc, pcszFilename));
2370 #endif
2371
2372 if (arc)
2373 doshClose(&pFile);
2374 else
2375 *ppFile = pFile;
2376 }
2377 else
2378 arc = ERROR_NOT_ENOUGH_MEMORY;
2379 }
2380 else
2381 if (!arc) // V0.9.19 (2002-04-02) [umoeller]
2382 arc = ERROR_INVALID_PARAMETER;
2383
2384 return (arc);
2385}
2386
2387/*
2388 *@@ doshReadAt:
2389 * reads cb bytes from the position specified by
2390 * lOffset into the buffer pointed to by pbData,
2391 * which should be cb bytes in size.
2392 *
2393 * Note that lOffset is always considered to
2394 * be from the beginning of the file (FILE_BEGIN
2395 * method).
2396 *
2397 * This implements a small cache so that several
2398 * calls with a near offset will not touch the
2399 * disk always. The cache has been optimized for
2400 * the exeh* functions and works quite nicely
2401 * there.
2402 *
2403 * Note that the position of the file pointer is
2404 * undefined after calling this function because
2405 * the data might have been returned from the
2406 * cache.
2407 *
2408 * fl may be any combination of the following:
2409 *
2410 * -- DRFL_NOCACHE: do not fill the cache with
2411 * new data if the data is not in the cache
2412 * currently.
2413 *
2414 * -- DRFL_FAILIFLESS: return ERROR_NO_DATA
2415 * if the data returned by DosRead is less
2416 * than what was specified. This might
2417 * simplify error handling.
2418 *
2419 *@@added V0.9.13 (2001-06-14) [umoeller]
2420 *@@changed V0.9.16 (2001-12-18) [umoeller]: now with XFILE, and always using FILE_BEGIN
2421 *@@chaanged V0.9.19 (2002-04-02) [umoeller]: added params checking
2422 */
2423
2424APIRET doshReadAt(PXFILE pFile,
2425 ULONG ulOffset, // in: offset to read from (from beginning of file)
2426 PULONG pcb, // in: bytes to read, out: bytes read (req.)
2427 PBYTE pbData, // out: read buffer (must be cb bytes)
2428 ULONG fl) // in: DRFL_* flags
2429{
2430 APIRET arc = NO_ERROR;
2431 ULONG cb;
2432 ULONG ulDummy;
2433
2434 if (!pFile || !pcb)
2435 // V0.9.19 (2002-04-02) [umoeller]
2436 return ERROR_INVALID_PARAMETER;
2437
2438 cb = *pcb;
2439 *pcb = 0;
2440
2441 // check if we have the data in the cache already;
2442
2443 if ( (pFile->pbCache)
2444 // first byte must be in cache
2445 && (ulOffset >= pFile->ulReadFrom)
2446 // last byte must be in cache
2447 && ( ulOffset + cb
2448 <= pFile->ulReadFrom + pFile->cbCache
2449 )
2450 )
2451 {
2452 // alright, return data from cache simply
2453 ULONG ulOfsInCache = ulOffset - pFile->ulReadFrom;
2454
2455 memcpy(pbData,
2456 pFile->pbCache + ulOfsInCache,
2457 cb);
2458 *pcb = cb;
2459
2460 #ifdef DEBUG_DOSOPEN
2461 _Pmpf((__FUNCTION__ " %s: data is fully in cache",
2462 pFile->pszFilename));
2463 _Pmpf((" caller wants %d bytes from %d",
2464 cb, ulOffset));
2465 _Pmpf((" we got %d bytes from %d",
2466 pFile->cbCache, pFile->ulReadFrom));
2467 _Pmpf((" so copied %d bytes from cache ofs %d",
2468 cb, ulOfsInCache));
2469 #endif
2470 }
2471 else
2472 {
2473 // data is not in cache:
2474 // check how much it is... for small amounts,
2475 // we load the cache first
2476 if ( (cb <= 4096 - 512)
2477 && (!(fl & DRFL_NOCACHE))
2478 )
2479 {
2480 #ifdef DEBUG_DOSOPEN
2481 _Pmpf((__FUNCTION__ " %s: filling cache anew",
2482 pFile->pszFilename));
2483 _Pmpf((" caller wants %d bytes from %d",
2484 cb, ulOffset));
2485 #endif
2486
2487 // OK, then fix the offset to read from
2488 // to a multiple of 512 to get a full sector
2489 pFile->ulReadFrom = ulOffset / 512L * 512L;
2490 // and read 4096 bytes always plus the
2491 // value we cut off above
2492 pFile->cbCache = 4096;
2493
2494 #ifdef DEBUG_DOSOPEN
2495 _Pmpf((" getting %d bytes from %d",
2496 pFile->cbCache, pFile->ulReadFrom));
2497 #endif
2498
2499 // free old cache
2500 if (pFile->pbCache)
2501 free(pFile->pbCache);
2502
2503 // allocate new cache
2504 if (!(pFile->pbCache = (PBYTE)malloc(pFile->cbCache)))
2505 arc = ERROR_NOT_ENOUGH_MEMORY;
2506 else
2507 {
2508 ULONG ulOfsInCache = 0;
2509
2510 if (!(arc = DosSetFilePtr(pFile->hf,
2511 (LONG)pFile->ulReadFrom,
2512 FILE_BEGIN,
2513 &ulDummy)))
2514 {
2515 if (!(arc = DosRead(pFile->hf,
2516 pFile->pbCache,
2517 pFile->cbCache,
2518 &ulDummy)))
2519 {
2520 // got data:
2521 #ifdef DEBUG_DOSOPEN
2522 _Pmpf((" %d bytes read", ulDummy));
2523 #endif
2524
2525 pFile->cbCache = ulDummy;
2526
2527 // check bounds
2528 ulOfsInCache = ulOffset - pFile->ulReadFrom;
2529
2530 /*
2531 if (ulOfsInCache + cb > pFile->cbCache)
2532 {
2533 cb = pFile->cbCache - ulOfsInCache;
2534 if (fl & DRFL_FAILIFLESS)
2535 arc = ERROR_NO_DATA;
2536 }
2537 */
2538 }
2539 }
2540
2541 if (!arc)
2542 {
2543 // copy to caller
2544 memcpy(pbData,
2545 pFile->pbCache + ulOfsInCache,
2546 cb);
2547 *pcb = cb;
2548
2549 #ifdef DEBUG_DOSOPEN
2550 _Pmpf((" so copied %d bytes from cache ofs %d",
2551 cb, ulOfsInCache));
2552 #endif
2553 }
2554 else
2555 {
2556 free(pFile->pbCache);
2557 pFile->pbCache = NULL;
2558 }
2559 } // end else if (!(pFile->pbCache = (PBYTE)malloc(pFile->cbCache)))
2560 }
2561 else
2562 {
2563 // read uncached:
2564 #ifdef DEBUG_DOSOPEN
2565 _Pmpf((" " __FUNCTION__ " %s: reading uncached",
2566 pFile->pszFilename));
2567 _Pmpf((" caller wants %d bytes from %d",
2568 cb, ulOffset));
2569 #endif
2570
2571 if (!(arc = DosSetFilePtr(pFile->hf,
2572 (LONG)ulOffset,
2573 FILE_BEGIN,
2574 &ulDummy)))
2575 {
2576 if (!(arc = DosRead(pFile->hf,
2577 pbData,
2578 cb,
2579 &ulDummy)))
2580 {
2581 if ( (fl & DRFL_FAILIFLESS)
2582 && (ulDummy != cb)
2583 )
2584 arc = ERROR_NO_DATA;
2585 else
2586 *pcb = ulDummy; // bytes read
2587 }
2588 }
2589 }
2590 }
2591
2592 return (arc);
2593}
2594
2595/*
2596 *@@ doshWrite:
2597 * writes the specified data to the file.
2598 * If (cb == 0), this runs strlen on pcsz
2599 * to find out the length.
2600 *
2601 * If the file is not in binary mode, all
2602 * \n chars are converted to \r\n before
2603 * writing.
2604 *
2605 * Note that this expects that the file
2606 * pointer is at the end of the file, or
2607 * you will get garbage.
2608 *
2609 *@@added V0.9.16 (2001-10-19) [umoeller]
2610 *@@changed V0.9.16 (2001-12-02) [umoeller]: added XOPEN_BINARY \r\n support
2611 *@@changed V0.9.16 (2001-12-06) [umoeller]: added check for pFile != NULL
2612 */
2613
2614APIRET doshWrite(PXFILE pFile,
2615 ULONG cb,
2616 PCSZ pbData)
2617{
2618 APIRET arc = NO_ERROR;
2619 if ((!pFile) || (!pbData))
2620 arc = ERROR_INVALID_PARAMETER;
2621 else
2622 {
2623 if (!cb)
2624 cb = strlen(pbData);
2625
2626 if (!cb)
2627 arc = ERROR_INVALID_PARAMETER;
2628 else
2629 {
2630 PSZ pszNew = NULL;
2631
2632 if (!(pFile->flOpenMode & XOPEN_BINARY))
2633 {
2634 // convert all \n to \r\n:
2635 // V0.9.16 (2001-12-02) [umoeller]
2636
2637 // count all \n first
2638 ULONG cNewLines = 0;
2639 PCSZ pSource = pbData;
2640 ULONG ul;
2641 for (ul = 0;
2642 ul < cb;
2643 ul++)
2644 {
2645 if (*pSource++ == '\n')
2646 cNewLines++;
2647 }
2648
2649 if (cNewLines)
2650 {
2651 // we have '\n' chars:
2652 // then we need just as many \r chars inserted
2653 ULONG cbNew = cb + cNewLines;
2654 if (!(pszNew = (PSZ)malloc(cbNew)))
2655 arc = ERROR_NOT_ENOUGH_MEMORY;
2656 else
2657 {
2658 PSZ pTarget = pszNew;
2659 pSource = pbData;
2660 for (ul = 0;
2661 ul < cb;
2662 ul++)
2663 {
2664 CHAR c = *pSource++;
2665 if (c == '\n')
2666 *pTarget++ = '\r';
2667 *pTarget++ = c;
2668 }
2669
2670 cb = cbNew;
2671 }
2672 }
2673 }
2674
2675 if (!arc)
2676 {
2677 ULONG cbWritten;
2678 if (!(arc = DosWrite(pFile->hf,
2679 (pszNew)
2680 ? pszNew
2681 : (PSZ)pbData,
2682 cb,
2683 &cbWritten)))
2684 {
2685 pFile->cbCurrent += cbWritten;
2686 // invalidate the cache
2687 FREE(pFile->pbCache);
2688 }
2689 }
2690
2691 if (pszNew)
2692 free(pszNew);
2693 }
2694 }
2695
2696 return (arc);
2697}
2698
2699/*
2700 *@@ doshWriteAt:
2701 * writes cb bytes (pointed to by pbData) to the
2702 * specified file at the position lOffset (from
2703 * the beginning of the file).
2704 *
2705 *@@added V0.9.13 (2001-06-14) [umoeller]
2706 */
2707
2708APIRET doshWriteAt(PXFILE pFile,
2709 ULONG ulOffset, // in: offset to write at
2710 ULONG cb, // in: bytes to write
2711 PCSZ pbData) // in: ptr to bytes to write (must be cb bytes)
2712{
2713 APIRET arc = NO_ERROR;
2714 ULONG cbWritten;
2715 if (!(arc = DosSetFilePtr(pFile->hf,
2716 (LONG)ulOffset,
2717 FILE_BEGIN,
2718 &cbWritten)))
2719 {
2720 if (!(arc = DosWrite(pFile->hf,
2721 (PSZ)pbData,
2722 cb,
2723 &cbWritten)))
2724 {
2725 if (ulOffset + cbWritten > pFile->cbCurrent)
2726 pFile->cbCurrent = ulOffset + cbWritten;
2727 // invalidate the cache V0.9.19 (2002-04-02) [umoeller]
2728 FREE(pFile->pbCache);
2729 }
2730 }
2731
2732 return (arc);
2733}
2734
2735/*
2736 *@@ doshWriteLogEntry
2737 * writes a log string to an XFILE, adding a
2738 * leading timestamp before the line.
2739 *
2740 * The internal string buffer is limited to 2000
2741 * characters. Length checking is _not_ performed.
2742 *
2743 *@@added V0.9.16 (2001-10-19) [umoeller]
2744 *@@changed V0.9.16 (2001-12-06) [umoeller]: added check for pFile != NULL
2745 */
2746
2747APIRET doshWriteLogEntry(PXFILE pFile,
2748 const char* pcszFormat,
2749 ...)
2750{
2751 APIRET arc = NO_ERROR;
2752
2753 if ((!pFile) || (!pcszFormat))
2754 arc = ERROR_INVALID_PARAMETER;
2755 else
2756 {
2757 DATETIME dt;
2758 CHAR szTemp[2000];
2759 ULONG ulLength;
2760
2761 DosGetDateTime(&dt);
2762 if (ulLength = sprintf(szTemp,
2763 "%04d-%02d-%02d %02d:%02d:%02d:%02d ",
2764 dt.year, dt.month, dt.day,
2765 dt.hours, dt.minutes, dt.seconds, dt.hundredths))
2766 {
2767 if (!(arc = doshWrite(pFile,
2768 ulLength,
2769 szTemp)))
2770 {
2771 va_list arg_ptr;
2772 va_start(arg_ptr, pcszFormat);
2773 ulLength = vsprintf(szTemp, pcszFormat, arg_ptr);
2774 va_end(arg_ptr);
2775
2776 if (pFile->flOpenMode & XOPEN_BINARY)
2777 // if we're in binary mode, we need to add \r too
2778 szTemp[ulLength++] = '\r';
2779 szTemp[ulLength++] = '\n';
2780
2781 arc = doshWrite(pFile,
2782 ulLength,
2783 szTemp);
2784 }
2785 }
2786 }
2787
2788 return (arc);
2789}
2790
2791/*
2792 * doshClose:
2793 * closes an XFILE opened by doshOpen and
2794 * sets *ppFile to NULL.
2795 *
2796 *@@added V0.9.16 (2001-10-19) [umoeller]
2797 */
2798
2799APIRET doshClose(PXFILE *ppFile)
2800{
2801 APIRET arc = NO_ERROR;
2802 PXFILE pFile;
2803
2804 if ( (ppFile)
2805 && (pFile = *ppFile)
2806 )
2807 {
2808 // set the ptr to NULL
2809 *ppFile = NULL;
2810
2811 FREE(pFile->pbCache);
2812 FREE(pFile->pszFilename);
2813
2814 if (pFile->hf)
2815 {
2816 DosSetFileSize(pFile->hf, pFile->cbCurrent);
2817 DosClose(pFile->hf);
2818 pFile->hf = NULLHANDLE;
2819 }
2820
2821 free(pFile);
2822 }
2823 else
2824 arc = ERROR_INVALID_PARAMETER;
2825
2826 return (arc);
2827}
2828
2829/*
2830 *@@ doshLoadTextFile:
2831 * reads a text file from disk, allocates memory
2832 * via malloc() and sets a pointer to this
2833 * buffer (or NULL upon errors).
2834 *
2835 * This allocates one extra byte to make the
2836 * buffer null-terminated always. The buffer
2837 * is _not_ converted WRT the line format.
2838 *
2839 * If CTRL-Z (ASCII 26) is encountered in the
2840 * content, it is set to the null character
2841 * instead (V0.9.18).
2842 *
2843 * This returns the APIRET of DosOpen and DosRead.
2844 * If any error occured, no buffer was allocated.
2845 * Otherwise, you should free() the buffer when
2846 * no longer needed.
2847 *
2848 *@@changed V0.9.7 (2001-01-15) [umoeller]: renamed from doshReadTextFile
2849 *@@changed V0.9.16 (2002-01-05) [umoeller]: added pcbRead
2850 *@@changed V0.9.16 (2002-01-05) [umoeller]: rewritten using doshOpen
2851 *@@changed V0.9.18 (2002-03-08) [umoeller]: fixed ctrl-z (EOF) bug
2852 */
2853
2854APIRET doshLoadTextFile(PCSZ pcszFile, // in: file name to read
2855 PSZ* ppszContent, // out: newly allocated buffer with file's content
2856 PULONG pcbRead) // out: size of that buffer including null byte (ptr can be NULL)
2857{
2858 APIRET arc;
2859
2860 ULONG cbFile = 0;
2861 PXFILE pFile = NULL;
2862
2863 if (!(arc = doshOpen(pcszFile,
2864 XOPEN_READ_EXISTING,
2865 &cbFile,
2866 &pFile)))
2867 {
2868 PSZ pszContent;
2869 if (!(pszContent = (PSZ)malloc(cbFile + 1)))
2870 arc = ERROR_NOT_ENOUGH_MEMORY;
2871 else
2872 {
2873 ULONG cbRead = 0;
2874 if (!(arc = DosRead(pFile->hf,
2875 pszContent,
2876 cbFile,
2877 &cbRead)))
2878 {
2879 if (cbRead != cbFile)
2880 arc = ERROR_NO_DATA;
2881 else
2882 {
2883 PSZ p;
2884 pszContent[cbRead] = '\0';
2885
2886 // check if we have a ctrl-z (EOF) marker
2887 // this is present, for example, in config.sys
2888 // after install
2889 // V0.9.18 (2002-03-08) [umoeller]
2890 if (p = strchr(pszContent, '\26'))
2891 {
2892 *p = '\0';
2893 cbRead = p - pszContent;
2894 }
2895
2896 *ppszContent = pszContent;
2897 if (pcbRead)
2898 *pcbRead = cbRead + 1;
2899 }
2900 }
2901
2902 if (arc)
2903 free(pszContent);
2904 }
2905
2906 doshClose(&pFile);
2907 }
2908
2909 return (arc);
2910}
2911
2912/*
2913 *@@ doshCreateBackupFileName:
2914 * creates a valid backup filename of pszExisting
2915 * with a numerical file name extension which does
2916 * not exist in the directory where pszExisting
2917 * resides.
2918 * Returns a PSZ to a new buffer which was allocated
2919 * using malloc().
2920 *
2921 * <B>Example:</B> returns "C:\CONFIG.002" for input
2922 * "C:\CONFIG.SYS" if "C:\CONFIG.001" already exists.
2923 *
2924 *@@changed V0.9.1 (99-12-13) [umoeller]: this crashed if pszExisting had no file extension
2925 */
2926
2927PSZ doshCreateBackupFileName(const char* pszExisting)
2928{
2929 CHAR szFilename[CCHMAXPATH];
2930 PSZ pszLastDot;
2931 ULONG ulCount = 1;
2932 CHAR szCount[5];
2933 ULONG ulDummy;
2934
2935 strcpy(szFilename, pszExisting);
2936
2937 if (!(pszLastDot = strrchr(szFilename, '.')))
2938 // no dot in filename:
2939 pszLastDot = szFilename + strlen(szFilename);
2940
2941 do
2942 {
2943 sprintf(szCount, ".%03lu", ulCount);
2944 strcpy(pszLastDot, szCount);
2945 ulCount++;
2946 } while (!doshQueryPathSize(szFilename, &ulDummy));
2947
2948 return (strdup(szFilename));
2949}
2950
2951/*
2952 *@@ doshCreateTempFileName:
2953 * produces a file name in the the specified directory
2954 * or $(TEMP) which presently doesn't exist. This
2955 * checks the directory for existing files, but does
2956 * not open the temp file.
2957 *
2958 * If (pcszDir != NULL), we look into that directory.
2959 * Otherwise we look into the directory specified
2960 * by the $(TEMP) environment variable.
2961 * If $(TEMP) is not set, $(TMP) is tried next.
2962 *
2963 * If the directory thus specified does not exist, the
2964 * root directory of the boot drive is used instead.
2965 * As a result, this function should be fairly bomb-proof.
2966 *
2967 * If (pcszExt != NULL), the temp file receives
2968 * that extension, or no extension otherwise.
2969 * Do not specify the dot in pcszExt.
2970 *
2971 * pszTempFileName receives the fully qualified
2972 * file name of the temp file in that directory
2973 * and must point to a buffer CCHMAXPATH in size.
2974 * The file name is 8+3 compliant if pcszExt does
2975 * not exceed three characters.
2976 *
2977 * If (pcszPrefix != NULL), the temp file name
2978 * is prefixed with pcszPrefix. Since the temp
2979 * file name must not exceed 8+3 letters, we
2980 * can only use ( 8 - strlen(pcszPrefix ) digits
2981 * for a random number to make the temp file name
2982 * unique. You must therefore use a maximum of
2983 * four characters for the prefix. Otherwise
2984 * ERROR_INVALID_PARAMETER is returned.
2985 *
2986 * Example: Assuming TEMP is set to C:\TEMP,
2987 +
2988 + doshCreateTempFileName(szBuffer,
2989 + NULL, // use $(TEMP)
2990 + "pre", // prefix
2991 + "tmp") // extension
2992 +
2993 * would produce something like "C:\TEMP\pre07FG2.tmp".
2994 *
2995 *@@added V0.9.9 (2001-04-04) [umoeller]
2996 */
2997
2998APIRET doshCreateTempFileName(PSZ pszTempFileName, // out: fully q'fied temp file name
2999 PCSZ pcszDir, // in: dir or NULL for %TEMP%
3000 PCSZ pcszPrefix, // in: prefix for temp file or NULL
3001 PCSZ pcszExt) // in: extension (without dot) or NULL
3002{
3003 APIRET arc = NO_ERROR;
3004
3005 ULONG ulPrefixLen = (pcszPrefix)
3006 ? strlen(pcszPrefix)
3007 : 0;
3008
3009 if ( (!pszTempFileName)
3010 || (ulPrefixLen > 4)
3011 )
3012 arc = ERROR_INVALID_PARAMETER;
3013 else
3014 {
3015 CHAR szDir[CCHMAXPATH] = "";
3016 FILESTATUS3 fs3;
3017
3018 const char *pcszTemp = pcszDir;
3019
3020 if (!pcszTemp)
3021 {
3022 if (!(pcszTemp = getenv("TEMP")))
3023 pcszTemp = getenv("TMP");
3024 }
3025
3026 if (pcszTemp) // either pcszDir or $(TEMP) or $(TMP) now
3027 if (DosQueryPathInfo((PSZ)pcszTemp,
3028 FIL_STANDARD,
3029 &fs3,
3030 sizeof(fs3)))
3031 // TEMP doesn't exist:
3032 pcszTemp = NULL;
3033
3034 if (!pcszTemp)
3035 // not set, or doesn't exist:
3036 // use root directory on boot drive
3037 sprintf(szDir,
3038 "%c:\\",
3039 doshQueryBootDrive());
3040 else
3041 {
3042 strcpy(szDir, pcszTemp);
3043 if (szDir[strlen(szDir) - 1] != '\\')
3044 strcat(szDir, "\\");
3045 }
3046
3047 if (!szDir[0])
3048 arc = ERROR_PATH_NOT_FOUND; // shouldn't happen
3049 else
3050 {
3051 ULONG ulRandom = 0;
3052 ULONG cAttempts = 0;
3053
3054 // produce random number
3055 DosQuerySysInfo(QSV_MS_COUNT,
3056 QSV_MS_COUNT,
3057 &ulRandom,
3058 sizeof(ulRandom));
3059
3060 do
3061 {
3062 CHAR szFile[20] = "",
3063 szFullTryThis[CCHMAXPATH];
3064
3065 // use the lower eight hex digits of the
3066 // system uptime as the temp dir name
3067 sprintf(szFile,
3068 "%08lX",
3069 ulRandom & 0xFFFFFFFF);
3070
3071 // if prefix is specified, overwrite the
3072 // first characters in the random number
3073 if (pcszPrefix)
3074 memcpy(szFile, pcszPrefix, ulPrefixLen);
3075
3076 if (pcszExt)
3077 {
3078 szFile[8] = '.';
3079 strcpy(szFile + 9, pcszExt);
3080 }
3081
3082 // now compose full temp file name
3083 strcpy(szFullTryThis, szDir);
3084 strcat(szFullTryThis, szFile);
3085 // now we have: "C:\temp\wpiXXXXX"
3086 if (DosQueryPathInfo(szFullTryThis,
3087 FIL_STANDARD,
3088 &fs3,
3089 sizeof(fs3))
3090 == ERROR_FILE_NOT_FOUND)
3091 {
3092 // file or dir doesn't exist:
3093 // cool, we're done
3094 strcpy(pszTempFileName, szFullTryThis);
3095 return (NO_ERROR);
3096 }
3097
3098 // if this didn't work, raise ulRandom and try again
3099 ulRandom += 123;
3100
3101 // try only 100 times, just to be sure
3102 cAttempts++;
3103 } while (cAttempts < 100);
3104
3105 // 100 loops elapsed:
3106 arc = ERROR_BAD_FORMAT;
3107 }
3108 }
3109
3110 return (arc);
3111}
3112
3113/*
3114 *@@ doshWriteTextFile:
3115 * writes a text file to disk; pszFile must contain the
3116 * whole path and filename.
3117 *
3118 * An existing file will be backed up if (pszBackup != NULL),
3119 * using doshCreateBackupFileName. In that case, pszBackup
3120 * receives the name of the backup created, so that buffer
3121 * should be CCHMAXPATH in size.
3122 *
3123 * If (pszbackup == NULL), an existing file will be overwritten.
3124 *
3125 * On success (NO_ERROR returned), *pulWritten receives
3126 * the no. of bytes written.
3127 *
3128 *@@changed V0.9.3 (2000-05-01) [umoeller]: optimized DosOpen; added error checking; changed prototype
3129 *@@changed V0.9.3 (2000-05-12) [umoeller]: added pszBackup
3130 */
3131
3132APIRET doshWriteTextFile(const char* pszFile, // in: file name
3133 const char* pszContent, // in: text to write
3134 PULONG pulWritten, // out: bytes written (ptr can be NULL)
3135 PSZ pszBackup) // in/out: create-backup?
3136{
3137 APIRET arc = NO_ERROR;
3138 ULONG ulWritten = 0;
3139
3140 if ((!pszFile) || (!pszContent))
3141 arc = ERROR_INVALID_PARAMETER;
3142 else
3143 {
3144 ULONG ulAction = 0,
3145 ulLocal = 0;
3146 HFILE hFile = 0;
3147
3148 ULONG ulSize = strlen(pszContent); // exclude 0 byte
3149
3150 if (pszBackup)
3151 {
3152 PSZ pszBackup2 = doshCreateBackupFileName(pszFile);
3153 DosCopy((PSZ)pszFile,
3154 pszBackup2,
3155 DCPY_EXISTING); // delete existing
3156 strcpy(pszBackup, pszBackup2);
3157 free(pszBackup2);
3158 }
3159
3160 if (!(arc = DosOpen((PSZ)pszFile,
3161 &hFile,
3162 &ulAction, // action taken
3163 ulSize, // primary allocation size
3164 FILE_ARCHIVED | FILE_NORMAL, // file attribute
3165 OPEN_ACTION_CREATE_IF_NEW
3166 | OPEN_ACTION_REPLACE_IF_EXISTS, // open flags
3167 OPEN_FLAGS_NOINHERIT
3168 | OPEN_FLAGS_SEQUENTIAL // sequential, not random access
3169 | OPEN_SHARE_DENYWRITE // deny write mode
3170 | OPEN_ACCESS_WRITEONLY, // write mode
3171 NULL))) // no EAs
3172 {
3173 if (!(arc = DosSetFilePtr(hFile,
3174 0L,
3175 FILE_BEGIN,
3176 &ulLocal)))
3177 if (!(arc = DosWrite(hFile,
3178 (PVOID)pszContent,
3179 ulSize,
3180 &ulWritten)))
3181 arc = DosSetFileSize(hFile, ulSize);
3182
3183 DosClose(hFile);
3184 }
3185 } // end if ((pszFile) && (pszContent))
3186
3187 if (pulWritten)
3188 *pulWritten = ulWritten;
3189
3190 return (arc);
3191}
3192
3193/*
3194 *@@category: Helpers\Control program helpers\Directory management
3195 * directory helpers (querying, creating, deleting etc.).
3196 */
3197
3198/* ******************************************************************
3199 *
3200 * Directory helpers
3201 *
3202 ********************************************************************/
3203
3204/*
3205 *@@ doshQueryDirExist:
3206 * returns TRUE if the given directory
3207 * exists and really is a directory.
3208 */
3209
3210BOOL doshQueryDirExist(PCSZ pcszDir)
3211{
3212 FILESTATUS3 fs3;
3213 APIRET arc;
3214
3215 if (!(arc = DosQueryPathInfo((PSZ)pcszDir,
3216 FIL_STANDARD,
3217 &fs3,
3218 sizeof(fs3))))
3219 // file found:
3220 return ((fs3.attrFile & FILE_DIRECTORY) != 0);
3221 else
3222 return FALSE;
3223}
3224
3225/*
3226 *@@ doshCreatePath:
3227 * this creates the specified directory.
3228 * As opposed to DosCreateDir, this
3229 * function can create several directories
3230 * at the same time, if the parent
3231 * directories do not exist yet.
3232 */
3233
3234APIRET doshCreatePath(PCSZ pcszPath,
3235 BOOL fHidden) // in: if TRUE, the new directories will get FILE_HIDDEN
3236{
3237 APIRET arc0 = NO_ERROR;
3238 CHAR path[CCHMAXPATH];
3239 CHAR *cp, c;
3240 ULONG cbPath;
3241
3242 strcpy(path, pcszPath);
3243 cbPath = strlen(path);
3244
3245 if (path[cbPath] != '\\')
3246 {
3247 path[cbPath] = '\\';
3248 path[cbPath+1] = 0;
3249 }
3250
3251 cp = path;
3252 // advance past the drive letter only if we have one
3253 if (*(cp+1) == ':')
3254 cp += 3;
3255
3256 // go!
3257 while (*cp != 0)
3258 {
3259 if (*cp == '\\')
3260 {
3261 c = *cp;
3262 *cp = 0;
3263 if (!doshQueryDirExist(path))
3264 {
3265 APIRET arc = DosCreateDir(path,
3266 0); // no EAs
3267 if (arc != NO_ERROR)
3268 {
3269 arc0 = arc;
3270 break;
3271 }
3272 else
3273 if (fHidden)
3274 {
3275 // hide the directory we just created
3276 doshSetPathAttr(path, FILE_HIDDEN);
3277 }
3278 }
3279 *cp = c;
3280 }
3281 cp++;
3282 }
3283 return (arc0);
3284}
3285
3286/*
3287 *@@ doshQueryCurrentDir:
3288 * writes the current directory into
3289 * the specified buffer, which should be
3290 * CCHMAXPATH in size.
3291 *
3292 * As opposed to DosQueryCurrentDir, this
3293 * includes the drive letter.
3294 *
3295 *@@added V0.9.4 (2000-07-22) [umoeller]
3296 */
3297
3298APIRET doshQueryCurrentDir(PSZ pszBuf)
3299{
3300 APIRET arc = NO_ERROR;
3301 ULONG ulCurDisk = 0;
3302 ULONG ulMap = 0;
3303 if (!(arc = DosQueryCurrentDisk(&ulCurDisk, &ulMap)))
3304 {
3305 ULONG cbBuf = CCHMAXPATH - 3;
3306 pszBuf[0] = ulCurDisk + 'A' - 1;
3307 pszBuf[1] = ':';
3308 pszBuf[2] = '\\';
3309 pszBuf[3] = '\0';
3310 arc = DosQueryCurrentDir(0, pszBuf + 3, &cbBuf);
3311 }
3312
3313 return (arc);
3314}
3315
3316/*
3317 *@@ doshDeleteDir:
3318 * deletes a directory. As opposed to DosDeleteDir,
3319 * this removes empty subdirectories and/or files
3320 * as well.
3321 *
3322 * flFlags can be any combination of the following:
3323 *
3324 * -- DOSHDELDIR_RECURSE: recurse into subdirectories.
3325 *
3326 * -- DOSHDELDIR_DELETEFILES: delete all regular files
3327 * which are found on the way.
3328 *
3329 * THIS IS NOT IMPLEMENTED YET.
3330 *
3331 * If 0 is specified, this effectively behaves just as
3332 * DosDeleteDir.
3333 *
3334 * If you specify DOSHDELDIR_RECURSE only, only empty
3335 * subdirectories are deleted as well.
3336 *
3337 * If you specify DOSHDELDIR_RECURSE | DOSHDELDIR_DELETEFILES,
3338 * this removes an entire directory tree, including all
3339 * subdirectories and files.
3340 *
3341 *@@added V0.9.4 (2000-07-01) [umoeller]
3342 */
3343
3344APIRET doshDeleteDir(PCSZ pcszDir,
3345 ULONG flFlags,
3346 PULONG pulDirs, // out: directories found
3347 PULONG pulFiles) // out: files found
3348{
3349 APIRET arc = NO_ERROR,
3350 arcReturn = NO_ERROR;
3351
3352 HDIR hdirFindHandle = HDIR_CREATE;
3353 FILEFINDBUF3 ffb3 = {0}; // returned from FindFirst/Next
3354 ULONG ulResultBufLen = sizeof(FILEFINDBUF3);
3355 ULONG ulFindCount = 1; // look for 1 file at a time
3356
3357 CHAR szFileMask[2*CCHMAXPATH];
3358 sprintf(szFileMask, "%s\\*", pcszDir);
3359
3360 // find files
3361 arc = DosFindFirst(szFileMask,
3362 &hdirFindHandle, // directory search handle
3363 FILE_ARCHIVED | FILE_DIRECTORY | FILE_SYSTEM
3364 | FILE_HIDDEN | FILE_READONLY,
3365 // search attributes; include all, even dirs
3366 &ffb3, // result buffer
3367 ulResultBufLen, // result buffer length
3368 &ulFindCount, // number of entries to find
3369 FIL_STANDARD); // return level 1 file info
3370
3371 if (arc == NO_ERROR)
3372 {
3373 // keep finding the next file until there are no more files
3374 while (arc == NO_ERROR) // != ERROR_NO_MORE_FILES
3375 {
3376 if (ffb3.attrFile & FILE_DIRECTORY)
3377 {
3378 // we found a directory:
3379
3380 // ignore the pseudo-directories
3381 if ( (strcmp(ffb3.achName, ".") != 0)
3382 && (strcmp(ffb3.achName, "..") != 0)
3383 )
3384 {
3385 // real directory:
3386 if (flFlags & DOSHDELDIR_RECURSE)
3387 {
3388 // recurse!
3389 CHAR szSubDir[2*CCHMAXPATH];
3390 sprintf(szSubDir, "%s\\%s", pcszDir, ffb3.achName);
3391 arcReturn = doshDeleteDir(szSubDir,
3392 flFlags,
3393 pulDirs,
3394 pulFiles);
3395 // this removes ffb3.achName as well
3396 }
3397 else
3398 {
3399 // directory, but no recursion:
3400 // report "access denied"
3401 // (this is what OS/2 reports with DosDeleteDir as well)
3402 arcReturn = ERROR_ACCESS_DENIED; // 5
3403 (*pulDirs)++;
3404 }
3405 }
3406 }
3407 else
3408 {
3409 // it's a file:
3410 arcReturn = ERROR_ACCESS_DENIED;
3411 (*pulFiles)++;
3412 }
3413
3414 if (arc == NO_ERROR)
3415 {
3416 ulFindCount = 1; // reset find count
3417 arc = DosFindNext(hdirFindHandle, // directory handle
3418 &ffb3, // result buffer
3419 ulResultBufLen, // result buffer length
3420 &ulFindCount); // number of entries to find
3421 }
3422 } // endwhile
3423
3424 DosFindClose(hdirFindHandle); // close our find handle
3425 }
3426
3427 if (arcReturn == NO_ERROR)
3428 // success so far:
3429 // delete our directory now
3430 arcReturn = DosDeleteDir((PSZ)pcszDir);
3431
3432 return (arcReturn);
3433}
3434
3435/*
3436 *@@category: Helpers\Control program helpers\Module handling
3437 * helpers for importing functions from a module (DLL).
3438 */
3439
3440/* ******************************************************************
3441 *
3442 * Module handling helpers
3443 *
3444 ********************************************************************/
3445
3446/*
3447 *@@ doshQueryProcAddr:
3448 * attempts to resolve the given procedure from
3449 * the given module name. Saves you from querying
3450 * the module handle and all that.
3451 *
3452 * This is intended for resolving undocumented
3453 * APIs from OS/2 system DLls such as PMMERGE
3454 * and DOSCALLS. It is assumed that the specified
3455 * module is already loaded.
3456 *
3457 * Returns:
3458 *
3459 * -- NO_ERROR
3460 *
3461 * -- ERROR_INVALID_NAME
3462 *
3463 * -- ERROR_INVALID_ORDINAL
3464 *
3465 * plus the error codes of DosLoadModule.
3466 *
3467 *@@added V0.9.16 (2002-01-13) [umoeller]
3468 */
3469
3470APIRET doshQueryProcAddr(PCSZ pcszModuleName, // in: module name (e.g. "PMMERGE")
3471 ULONG ulOrdinal, // in: proc ordinal
3472 PFN *ppfn) // out: proc address
3473{
3474 HMODULE hmod;
3475 APIRET arc;
3476 if (!(arc = DosQueryModuleHandle((PSZ)pcszModuleName,
3477 &hmod)))
3478 {
3479 if ((arc = DosQueryProcAddr(hmod,
3480 ulOrdinal,
3481 NULL,
3482 ppfn)))
3483 {
3484 // the CP programming guide and reference says use
3485 // DosLoadModule if DosQueryProcAddr fails with this error
3486 if (arc == ERROR_INVALID_HANDLE)
3487 {
3488 if (!(arc = DosLoadModule(NULL,
3489 0,
3490 (PSZ)pcszModuleName,
3491 &hmod)))
3492 {
3493 arc = DosQueryProcAddr(hmod,
3494 ulOrdinal,
3495 NULL,
3496 ppfn);
3497 }
3498 }
3499 }
3500 }
3501
3502 return (arc);
3503}
3504
3505/*
3506 *@@ doshResolveImports:
3507 * this function loads the module called pszModuleName
3508 * and resolves imports dynamically using DosQueryProcAddress.
3509 *
3510 * To specify the functions to be imported, a RESOLVEFUNCTION
3511 * array is used. In each of the array items, specify the
3512 * name of the function and a pointer to a function pointer
3513 * where to store the resolved address.
3514 *
3515 *@@added V0.9.3 (2000-04-29) [umoeller]
3516 */
3517
3518APIRET doshResolveImports(PCSZ pcszModuleName, // in: DLL to load
3519 HMODULE *phmod, // out: module handle
3520 PCRESOLVEFUNCTION paResolves, // in/out: function resolves
3521 ULONG cResolves) // in: array item count (not array size!)
3522{
3523 CHAR szName[CCHMAXPATH];
3524 APIRET arc;
3525
3526 if (!(arc = DosLoadModule(szName,
3527 sizeof(szName),
3528 (PSZ)pcszModuleName,
3529 phmod)))
3530 {
3531 ULONG ul;
3532 for (ul = 0;
3533 ul < cResolves;
3534 ul++)
3535 {
3536 if (arc = DosQueryProcAddr(*phmod,
3537 0, // ordinal, ignored
3538 (PSZ)paResolves[ul].pcszFunctionName,
3539 paResolves[ul].ppFuncAddress))
3540 // error:
3541 break;
3542 }
3543
3544 if (arc)
3545 // V0.9.16 (2001-12-08) [umoeller]
3546 DosFreeModule(*phmod);
3547 }
3548
3549 return (arc);
3550}
3551
3552/*
3553 *@@category: Helpers\Control program helpers\Performance (CPU load) helpers
3554 * helpers around DosPerfSysCall.
3555 */
3556
3557/* ******************************************************************
3558 *
3559 * Performance Counters (CPU Load)
3560 *
3561 ********************************************************************/
3562
3563/*
3564 *@@ doshPerfOpen:
3565 * initializes the OS/2 DosPerfSysCall API for
3566 * the calling thread.
3567 *
3568 * Note: This API is not supported on all OS/2
3569 * versions. I believe it came up with some Warp 4
3570 * fixpak. The API is resolved dynamically by
3571 * this function (using DosQueryProcAddr).
3572 *
3573 * This properly initializes the internal counters
3574 * which the OS/2 kernel uses for this API. Apparently,
3575 * with newer kernels (FP13/14), IBM has chosen to no
3576 * longer do this automatically, which is the reason
3577 * why many "pulse" utilities display garbage with these
3578 * fixpaks.
3579 *
3580 * After NO_ERROR is returned, DOSHPERFSYS.cProcessors
3581 * contains the no. of processors found on the system.
3582 * All pointers in DOSHPERFSYS then point to arrays
3583 * which have exactly cProcessors array items.
3584 *
3585 * So after NO_ERROR was returned here, you can keep
3586 * calling doshPerfGet to get a current snapshot of the
3587 * IRQ and user loads for each CPU. Note that interrupts
3588 * are only processed on CPU 0 on SMP systems.
3589 *
3590 * Call doshPerfClose to clean up resources allocated
3591 * by this function.
3592 *
3593 * For more sample code, take a look at the "Pulse" widget
3594 * in the XWorkplace sources (src\xcenter\w_pulse.c).
3595 *
3596 * Example code:
3597 *
3598 + PDOSHPERFSYS pPerf = NULL;
3599 + APIRET arc;
3600 + if (!(arc = arc = doshPerfOpen(&pPerf)))
3601 + {
3602 + // this should really be in a timer,
3603 + // e.g. once per second
3604 + ULONG ulCPU;
3605 + if (!(arc = doshPerfGet(&pPerf)))
3606 + {
3607 + // go thru all CPUs
3608 + for (ulCPU = 0; ulCPU < pPerf->cProcessors; ulCPU++)
3609 + {
3610 + LONG lUserLoadThis = pPerf->palLoads[ulCPU];
3611 + ...
3612 + }
3613 + }
3614 +
3615 + // clean up
3616 + doshPerfClose(&pPerf);
3617 + }
3618 +
3619 *
3620 *@@added V0.9.7 (2000-12-02) [umoeller]
3621 *@@changed V0.9.9 (2001-03-14) [umoeller]: added interrupt loads; thanks phaller
3622 */
3623
3624APIRET doshPerfOpen(PDOSHPERFSYS *ppPerfSys) // out: new DOSHPERFSYS structure
3625{
3626 APIRET arc = NO_ERROR;
3627
3628 // allocate DOSHPERFSYS structure
3629 *ppPerfSys = (PDOSHPERFSYS)malloc(sizeof(DOSHPERFSYS));
3630 if (!*ppPerfSys)
3631 arc = ERROR_NOT_ENOUGH_MEMORY;
3632 else
3633 {
3634 // initialize structure
3635 PDOSHPERFSYS pPerfSys = *ppPerfSys;
3636 memset(pPerfSys, 0, sizeof(*pPerfSys));
3637
3638 // resolve DosPerfSysCall API entry
3639 if (!(arc = DosLoadModule(NULL, 0, "DOSCALLS", &pPerfSys->hmod)))
3640 {
3641 if (!(arc = DosQueryProcAddr(pPerfSys->hmod,
3642 976,
3643 "DosPerfSysCall",
3644 (PFN*)(&pPerfSys->pDosPerfSysCall))))
3645 {
3646 // OK, we got the API: initialize!
3647 if (!(arc = pPerfSys->pDosPerfSysCall(CMD_KI_ENABLE, 0, 0, 0)))
3648 {
3649 pPerfSys->fInitialized = TRUE;
3650 // call CMD_KI_DISABLE later
3651
3652 if (!(arc = pPerfSys->pDosPerfSysCall(CMD_PERF_INFO,
3653 0,
3654 (ULONG)(&pPerfSys->cProcessors),
3655 0)))
3656 {
3657 ULONG ul = 0,
3658 cProcs = pPerfSys->cProcessors,
3659 cbDouble = cProcs * sizeof(double),
3660 cbLong = cProcs * sizeof(LONG);
3661
3662 // allocate arrays
3663 if ( (!(pPerfSys->paCPUUtils = (PCPUUTIL)calloc(cProcs,
3664 sizeof(CPUUTIL))))
3665 || (!(pPerfSys->padBusyPrev
3666 = (double*)malloc(cbDouble)))
3667 || (!(pPerfSys->padTimePrev
3668 = (double*)malloc(cbDouble)))
3669 || (!(pPerfSys->padIntrPrev
3670 = (double*)malloc(cbDouble)))
3671 || (!(pPerfSys->palLoads
3672 = (PLONG)malloc(cbLong)))
3673 || (!(pPerfSys->palIntrs
3674 = (PLONG)malloc(cbLong)))
3675 )
3676 arc = ERROR_NOT_ENOUGH_MEMORY;
3677 else
3678 {
3679 for (ul = 0; ul < cProcs; ul++)
3680 {
3681 pPerfSys->padBusyPrev[ul] = 0.0;
3682 pPerfSys->padTimePrev[ul] = 0.0;
3683 pPerfSys->padIntrPrev[ul] = 0.0;
3684 pPerfSys->palLoads[ul] = 0;
3685 pPerfSys->palIntrs[ul] = 0;
3686 }
3687 }
3688 }
3689 }
3690 } // end if (arc == NO_ERROR)
3691 } // end if (arc == NO_ERROR)
3692
3693 if (arc)
3694 // error: clean up
3695 doshPerfClose(ppPerfSys);
3696
3697 } // end else if (!*ppPerfSys)
3698
3699 return (arc);
3700}
3701
3702/*
3703 *@@ doshPerfGet:
3704 * calculates a current snapshot of the system load,
3705 * compared with the load which was calculated on
3706 * the previous call.
3707 *
3708 * If you want to continually measure the system CPU
3709 * load, this is the function you will want to call
3710 * regularly -- e.g. with a timer once per second.
3711 *
3712 * Call this ONLY if doshPerfOpen returned NO_ERROR,
3713 * or you'll get crashes.
3714 *
3715 * If this call returns NO_ERROR, you get LONG load
3716 * values for each CPU in the system in the arrays
3717 * in DOSHPERFSYS (in per-mille, 0-1000).
3718 *
3719 * There are two arrays:
3720 *
3721 * -- DOSHPERFSYS.palLoads contains the "user" load
3722 * for each CPU.
3723 *
3724 * -- DOSHPERFSYS.palIntrs contains the "IRQ" load
3725 * for each CPU.
3726 *
3727 * Sum up the two values to get the total load for
3728 * each CPU.
3729 *
3730 * For example, if there are two CPUs, after this call,
3731 *
3732 * -- DOSHPERFSYS.palLoads[0] contains the "user" load
3733 * of the first CPU,
3734 *
3735 * -- DOSHPERFSYS.palLoads[0] contains the "user" load
3736 * of the second CPU.
3737 *
3738 * See doshPerfOpen for example code.
3739 *
3740 *@@added V0.9.7 (2000-12-02) [umoeller]
3741 *@@changed V0.9.9 (2001-03-14) [umoeller]: added interrupt loads; thanks phaller
3742 */
3743
3744APIRET doshPerfGet(PDOSHPERFSYS pPerfSys)
3745{
3746 APIRET arc = NO_ERROR;
3747 if (!pPerfSys->pDosPerfSysCall)
3748 arc = ERROR_INVALID_PARAMETER;
3749 else
3750 {
3751 if (!(arc = pPerfSys->pDosPerfSysCall(CMD_KI_RDCNT,
3752 (ULONG)pPerfSys->paCPUUtils,
3753 0, 0)))
3754 {
3755 // go thru all processors
3756 ULONG ul = 0;
3757 for (; ul < pPerfSys->cProcessors; ul++)
3758 {
3759 PCPUUTIL pCPUUtilThis = &pPerfSys->paCPUUtils[ul];
3760
3761 double dTime = LL2F(pCPUUtilThis->ulTimeHigh,
3762 pCPUUtilThis->ulTimeLow);
3763 double dBusy = LL2F(pCPUUtilThis->ulBusyHigh,
3764 pCPUUtilThis->ulBusyLow);
3765 double dIntr = LL2F(pCPUUtilThis->ulIntrHigh,
3766 pCPUUtilThis->ulIntrLow);
3767
3768 double *pdBusyPrevThis = &pPerfSys->padBusyPrev[ul];
3769 double *pdTimePrevThis = &pPerfSys->padTimePrev[ul];
3770 double *pdIntrPrevThis = &pPerfSys->padIntrPrev[ul];
3771
3772 // avoid division by zero
3773 double dTimeDelta;
3774 if (dTimeDelta = (dTime - *pdTimePrevThis))
3775 {
3776 pPerfSys->palLoads[ul]
3777 = (LONG)( (double)( (dBusy - *pdBusyPrevThis)
3778 / dTimeDelta
3779 * 1000.0
3780 )
3781 );
3782 pPerfSys->palIntrs[ul]
3783 = (LONG)( (double)( (dIntr - *pdIntrPrevThis)
3784 / dTimeDelta
3785 * 1000.0
3786 )
3787 );
3788 }
3789 else
3790 {
3791 // no clear readings are available
3792 pPerfSys->palLoads[ul] = 0;
3793 pPerfSys->palIntrs[ul] = 0;
3794 }
3795
3796 *pdTimePrevThis = dTime;
3797 *pdBusyPrevThis = dBusy;
3798 *pdIntrPrevThis = dIntr;
3799 }
3800 }
3801 }
3802
3803 return (arc);
3804}
3805
3806/*
3807 *@@ doshPerfClose:
3808 * frees all resources allocated by doshPerfOpen.
3809 *
3810 *@@added V0.9.7 (2000-12-02) [umoeller]
3811 *@@changed V0.9.9 (2001-02-06) [umoeller]: removed disable; this broke the WarpCenter
3812 *@@changed V0.9.9 (2001-03-14) [umoeller]: fixed memory leak
3813 *@@changed V0.9.9 (2001-03-14) [umoeller]: added interrupt loads; thanks phaller
3814 */
3815
3816APIRET doshPerfClose(PDOSHPERFSYS *ppPerfSys)
3817{
3818 APIRET arc = NO_ERROR;
3819 PDOSHPERFSYS pPerfSys;
3820 if ( (!ppPerfSys)
3821 || (!(pPerfSys = *ppPerfSys))
3822 )
3823 arc = ERROR_INVALID_PARAMETER;
3824 else
3825 {
3826 // do not call this, this messes up the WarpCenter V0.9.9 (2001-02-06) [umoeller]
3827 // if (pPerfSys->fInitialized) pPerfSys->pDosPerfSysCall(CMD_KI_DISABLE, 0, 0, 0);
3828
3829 if (pPerfSys->paCPUUtils)
3830 free(pPerfSys->paCPUUtils);
3831 if (pPerfSys->padBusyPrev)
3832 free(pPerfSys->padBusyPrev);
3833 if (pPerfSys->padTimePrev)
3834 free(pPerfSys->padTimePrev);
3835 if (pPerfSys->padIntrPrev)
3836 free(pPerfSys->padIntrPrev);
3837 if (pPerfSys->palLoads) // was missing V0.9.9 (2001-03-14) [umoeller]
3838 free(pPerfSys->palLoads);
3839 if (pPerfSys->palIntrs)
3840 free(pPerfSys->palIntrs);
3841
3842 if (pPerfSys->hmod)
3843 DosFreeModule(pPerfSys->hmod);
3844 free(pPerfSys);
3845 *ppPerfSys = NULL;
3846 }
3847
3848 return (arc);
3849}
3850
3851/*
3852 *@@category: Helpers\Control program helpers\Process management
3853 * helpers for starting subprocesses.
3854 */
3855
3856/* ******************************************************************
3857 *
3858 * Process helpers
3859 *
3860 ********************************************************************/
3861
3862static PVOID // G_pvGlobalInfoSeg = NULL,
3863 G_pvLocalInfoSeg = NULL;
3864
3865USHORT _Far16 _Pascal Dos16GetInfoSeg(PSEL pselGlobal,
3866 PSEL pselLocal);
3867
3868/*
3869 * GetInfoSegs:
3870 *
3871 */
3872
3873static VOID GetInfoSegs(VOID)
3874{
3875 SEL GlobalInfoSegSelector,
3876 LocalInfoSegSelector;
3877
3878 // get selectors (old 16-bit API; this gets called only once)
3879 Dos16GetInfoSeg(&GlobalInfoSegSelector,
3880 &LocalInfoSegSelector);
3881 // thunk
3882 /* G_pvGlobalInfoSeg = (PVOID)( (GlobalInfoSegSelector << 0x000D)
3883 & 0x01fff0000); */
3884 G_pvLocalInfoSeg = (PVOID)( (LocalInfoSegSelector << 0x000D)
3885 & 0x01fff0000);
3886}
3887
3888/*
3889 *@@ doshMyPID:
3890 * returns the PID of the current process.
3891 *
3892 * This uses an interesting hack which is way
3893 * faster than DosGetInfoBlocks.
3894 *
3895 *@@added V0.9.9 (2001-04-04) [umoeller]
3896 */
3897
3898ULONG doshMyPID(VOID)
3899{
3900 if (!G_pvLocalInfoSeg)
3901 // first call:
3902 GetInfoSegs();
3903
3904 // PID is at offset 0 in the local info seg
3905 return (*(PUSHORT)G_pvLocalInfoSeg);
3906}
3907
3908/*
3909 *@@ doshMyTID:
3910 * returns the TID of the current thread.
3911 *
3912 * This uses an interesting hack which is way
3913 * faster than DosGetInfoBlocks.
3914 *
3915 *@@added V0.9.9 (2001-04-04) [umoeller]
3916 */
3917
3918ULONG doshMyTID(VOID)
3919{
3920 if (!G_pvLocalInfoSeg)
3921 // first call:
3922 GetInfoSegs();
3923
3924 // TID is at offset 6 in the local info seg
3925 return (*(PUSHORT)((PBYTE)G_pvLocalInfoSeg + 6));
3926}
3927
3928/*
3929 *@@ doshExecVIO:
3930 * executes cmd.exe with the /c parameter
3931 * and pcszExecWithArgs. This is equivalent
3932 * to the C library system() function,
3933 * except that an OS/2 error code is returned
3934 * and that this works with the VAC subsystem
3935 * library.
3936 *
3937 * This uses DosExecPgm and handles the sick
3938 * argument passing.
3939 *
3940 * If NO_ERROR is returned, *plExitCode receives
3941 * the exit code of the process. If the process
3942 * was terminated abnormally, *plExitCode receives:
3943 *
3944 * -- -1: hard error halt
3945 * -- -2: 16-bit trap
3946 * -- -3: DosKillProcess
3947 * -- -4: 32-bit exception
3948 *
3949 *@@added V0.9.4 (2000-07-27) [umoeller]
3950 */
3951
3952APIRET doshExecVIO(PCSZ pcszExecWithArgs,
3953 PLONG plExitCode) // out: exit code (ptr can be NULL)
3954{
3955 APIRET arc = NO_ERROR;
3956
3957 if (strlen(pcszExecWithArgs) > 255)
3958 arc = ERROR_INSUFFICIENT_BUFFER;
3959 else
3960 {
3961 CHAR szObj[CCHMAXPATH];
3962 RESULTCODES res = {0};
3963 CHAR szBuffer[300];
3964
3965 // DosExecPgm expects two args in szBuffer:
3966 // -- cmd.exe\0
3967 // -- then the actual argument, terminated by two 0 bytes.
3968 memset(szBuffer, 0, sizeof(szBuffer));
3969 strcpy(szBuffer, "cmd.exe\0");
3970 sprintf(szBuffer + 8, "/c %s",
3971 pcszExecWithArgs);
3972
3973 arc = DosExecPgm(szObj, sizeof(szObj),
3974 EXEC_SYNC,
3975 szBuffer,
3976 0,
3977 &res,
3978 "cmd.exe");
3979 if ((arc == NO_ERROR) && (plExitCode))
3980 {
3981 if (res.codeTerminate == 0)
3982 // normal exit:
3983 *plExitCode = res.codeResult;
3984 else
3985 *plExitCode = -((LONG)res.codeTerminate);
3986 }
3987 }
3988
3989 return (arc);
3990}
3991
3992/*
3993 *@@ doshQuickStartSession:
3994 * this is a shortcut to DosStartSession w/out having to
3995 * deal with all the messy parameters.
3996 *
3997 * This one starts pszPath as a child session and passes
3998 * pszParams to it.
3999 *
4000 * In usPgmCtl, OR any or none of the following (V0.9.0):
4001 * -- SSF_CONTROL_NOAUTOCLOSE (0x0008): do not close automatically.
4002 * This bit is used only for VIO Windowable apps and ignored
4003 * for all other applications.
4004 * -- SSF_CONTROL_MINIMIZE (0x0004)
4005 * -- SSF_CONTROL_MAXIMIZE (0x0002)
4006 * -- SSF_CONTROL_INVISIBLE (0x0001)
4007 * -- SSF_CONTROL_VISIBLE (0x0000)
4008 *
4009 * Specifying 0 will therefore auto-close the session and make it
4010 * visible.
4011 *
4012 * If (fWait), this function will create a termination queue
4013 * and not return until the child session has ended. Be warned,
4014 * this blocks the calling thread.
4015 *
4016 * Otherwise the function will return immediately.
4017 *
4018 * The session and process IDs of the child session will be
4019 * written to *pulSID and *ppid. Of course, in "wait" mode,
4020 * these are no longer valid after this function returns.
4021 *
4022 * Returns the error code of DosStartSession.
4023 *
4024 * Note: According to CPREF, calling DosStartSession calls
4025 * DosExecPgm in turn for all full-screen, VIO, and PM sessions.
4026 *
4027 *@@changed V0.9.0 [umoeller]: prototype changed to include usPgmCtl
4028 *@@changed V0.9.1 (99-12-30) [umoeller]: queue was sometimes not closed. Fixed.
4029 *@@changed V0.9.3 (2000-05-03) [umoeller]: added fForeground
4030 *@@changed V0.9.14 (2001-08-03) [umoeller]: fixed potential queue leak
4031 *@@changed V0.9.14 (2001-08-03) [umoeller]: fixed memory leak in wait mode; added pusReturn to prototype
4032 */
4033
4034APIRET doshQuickStartSession(PCSZ pcszPath, // in: program to start
4035 PCSZ pcszParams, // in: parameters for program
4036 BOOL fForeground, // in: if TRUE, session will be in foreground
4037 USHORT usPgmCtl, // in: STARTDATA.PgmControl
4038 BOOL fWait, // in: wait for termination?
4039 PULONG pulSID, // out: session ID (req.)
4040 PPID ppid, // out: process ID (req.)
4041 PUSHORT pusReturn) // out: in wait mode, session's return code (ptr can be NULL)
4042{
4043 APIRET arc = NO_ERROR;
4044 // queue stuff
4045 const char *pcszQueueName = "\\queues\\xwphlpsw.que";
4046 HQUEUE hq = 0;
4047 PID qpid = 0;
4048
4049 if (fWait)
4050 {
4051 if (!(arc = DosCreateQueue(&hq,
4052 QUE_FIFO | QUE_CONVERT_ADDRESS,
4053 (PSZ)pcszQueueName)))
4054 arc = DosOpenQueue(&qpid, &hq, (PSZ)pcszQueueName);
4055 }
4056
4057 if (!arc) // V0.9.14 (2001-08-03) [umoeller]
4058 {
4059 STARTDATA SData;
4060 CHAR szObjBuf[CCHMAXPATH];
4061
4062 SData.Length = sizeof(STARTDATA);
4063 SData.Related = SSF_RELATED_CHILD; //INDEPENDENT;
4064 SData.FgBg = (fForeground) ? SSF_FGBG_FORE : SSF_FGBG_BACK;
4065 // V0.9.3 (2000-05-03) [umoeller]
4066 SData.TraceOpt = SSF_TRACEOPT_NONE;
4067
4068 SData.PgmTitle = (PSZ)pcszPath; // title for window
4069 SData.PgmName = (PSZ)pcszPath;
4070 SData.PgmInputs = (PSZ)pcszParams;
4071
4072 SData.TermQ = (fWait) ? (PSZ)pcszQueueName : NULL;
4073 SData.Environment = 0;
4074 SData.InheritOpt = SSF_INHERTOPT_PARENT;
4075 SData.SessionType = SSF_TYPE_DEFAULT;
4076 SData.IconFile = 0;
4077 SData.PgmHandle = 0;
4078
4079 SData.PgmControl = usPgmCtl;
4080
4081 SData.InitXPos = 30;
4082 SData.InitYPos = 40;
4083 SData.InitXSize = 200;
4084 SData.InitYSize = 140;
4085 SData.Reserved = 0;
4086 SData.ObjectBuffer = szObjBuf;
4087 SData.ObjectBuffLen = (ULONG)sizeof(szObjBuf);
4088
4089 if ( (!(arc = DosStartSession(&SData, pulSID, ppid)))
4090 && (fWait)
4091 )
4092 {
4093 // block on the termination queue, which is written
4094 // to when the subprocess ends
4095 REQUESTDATA rqdata;
4096 ULONG cbData = 0;
4097 PULONG pulData = NULL;
4098 BYTE elpri;
4099
4100 rqdata.pid = qpid;
4101 if (!(arc = DosReadQueue(hq, // in: queue handle
4102 &rqdata, // out: pid and ulData
4103 &cbData, // out: size of data returned
4104 (PVOID*)&pulData, // out: data returned
4105 0, // in: remove first element in queue
4106 0, // in: wait for queue data (block thread)
4107 &elpri, // out: element's priority
4108 0))) // in: event semaphore to be posted
4109 {
4110 if (!rqdata.ulData)
4111 {
4112 // child session ended:
4113 // V0.9.14 (2001-08-03) [umoeller]
4114
4115 // *pulSID = (*pulData) & 0xffff;
4116 if (pusReturn)
4117 *pusReturn = ((*pulData) >> 16) & 0xffff;
4118
4119 }
4120 // else: continue looping
4121
4122 if (pulData)
4123 DosFreeMem(pulData);
4124 }
4125 }
4126 }
4127
4128 if (hq)
4129 DosCloseQueue(hq);
4130
4131 return (arc);
4132}
4133
4134
Note: See TracBrowser for help on using the repository browser.