summaryrefslogtreecommitdiff
path: root/tools/bootstrp/command.cxx
blob: 138b5ffcffaf845c5703ebd63d36b4190d6e86fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"

#ifdef SCO
#define _IOSTREAM_H
#endif

#ifdef PRECOMPILED
#include "first.hxx"
#endif

#include <tools/fsys.hxx>
#include <tools/stream.hxx>
#include "bootstrp/command.hxx"
#include <tools/debug.hxx>
#include "bootstrp/appdef.hxx"

#ifdef _MSC_VER
#pragma warning (push,1)
#endif

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>

#ifdef _MSC_VER
#pragma warning (pop)
#endif

//#define MH_TEST2  1           // fuers direkte Testen

#if defined(WNT) || defined(OS2)
#ifdef _MSC_VER
#pragma warning (push,1)
#endif
#include <process.h>    // for _SPAWN
#ifdef _MSC_VER
#pragma warning (pop)
#endif
#endif
#ifdef UNX
#include <sys/types.h>
#include <unistd.h>
#if ( defined NETBSD ) || defined (FREEBSD) || defined (AIX) \
    || defined (HPUX) || defined (MACOSX) || defined (OPENBSD)
#include <sys/wait.h>
#else
#include <wait.h>
#endif
#define P_WAIT 1        // erstmal einen dummz
#endif

#if defined WNT
#include <tools/svwin.h>
#endif

#if defined(WNT) || defined(OS2)
#define     cPathSeperator ';'
#endif
#ifdef UNX
#define     cPathSeperator  ':'
#endif

/*****************************************************************************/
CommandLine::CommandLine(BOOL bWrite)
/*****************************************************************************/
                : bTmpWrite(bWrite)
{
    CommandBuffer = new char [1];
    if (CommandBuffer == NULL) {
        //cout << "Error: nospace" << endl;
        exit(0);
    }
    CommandBuffer[0] = '\0';
    nArgc = 0;
    ppArgv = new char * [1];
    ppArgv[0] = NULL;

    ComShell = new char [128];
    char* pTemp = getenv("COMMAND_SHELL");
    if(!pTemp)
        strcpy(ComShell,COMMAND_SHELL);
    else
        strcpy(ComShell,pTemp);

    strcpy(&ComShell[strlen(ComShell)]," -C ");
}

/*****************************************************************************/
CommandLine::CommandLine(const char *CommandString, BOOL bWrite)
/*****************************************************************************/
                : bTmpWrite(bWrite)
{
    CommandBuffer = new char [1];
    if (CommandBuffer == NULL) {
        //cout << "Error: nospace" << endl;
        exit(0);
    }
    nArgc = 0;
    ppArgv = new char * [1];
    ppArgv[0] = NULL;

    ComShell = new char [128];
    char* pTemp = getenv("COMMAND_SHELL");
    if(!pTemp)
        strcpy(ComShell,COMMAND_SHELL);
    else
        strcpy(ComShell,pTemp);

    strcpy(&ComShell[strlen(ComShell)]," -C ");

    BuildCommand(CommandString);
}

/*****************************************************************************/
CommandLine::CommandLine(const CommandLine& CCommandLine, BOOL bWrite)
/*****************************************************************************/
                : bTmpWrite(bWrite)
{
    CommandBuffer = new char [1];
    if (CommandBuffer == NULL) {
        //cout << "Error: nospace" << endl;
        exit(0);
    }
    nArgc = 0;
    ppArgv = new char * [1];
    ppArgv[0] = NULL;

    ComShell = new char [128];
    char* pTemp = getenv("COMMAND_SHELL");
    if(!pTemp)
        strcpy(ComShell,COMMAND_SHELL);
    else
        strcpy(ComShell,pTemp);

    strcpy(&ComShell[strlen(ComShell)]," -C ");

    BuildCommand(CCommandLine.CommandBuffer);
}

/*****************************************************************************/
CommandLine::~CommandLine()
/*****************************************************************************/
{
    delete [] CommandBuffer;
    delete [] ComShell;
    //for (int i = 0; ppArgv[i] != '\0'; i++) {
    for (int i = 0; ppArgv[i] != 0; i++) {
        delete [] ppArgv[i];
    }
    delete [] ppArgv;

}

/*****************************************************************************/
CommandLine& CommandLine::operator=(const CommandLine& CCommandLine)
/*****************************************************************************/
{
    strcpy (CommandBuffer, CCommandLine.CommandBuffer);
    for (int i = 0; i != nArgc; i++) {
        delete [] ppArgv[i];
    }
    delete [] ppArgv;
        ppArgv = new char * [1];
        ppArgv[0] = NULL;
    BuildCommand(CommandBuffer);
    return *this;
}

/*****************************************************************************/
CommandLine& CommandLine::operator=(const char *CommandString)
/*****************************************************************************/
{
    strcpy (CommandBuffer, CommandString);
    for (int i = 0; i != nArgc; i++) {
        delete [] ppArgv[i];
    }
    delete [] ppArgv;
        ppArgv = new char * [1];
        ppArgv[0] = NULL;
    BuildCommand(CommandBuffer);

    return *this;
}

/*****************************************************************************/
void CommandLine::Print()
/*****************************************************************************/
{
    //cout << "******* start print *******" << endl;
    //cout << "nArgc = " << nArgc << endl;
    //cout << "CommandBuffer = " << CommandBuffer << endl;
    for (int i = 0; ppArgv[i] != NULL; i++) {
        //cout << "ppArgv[" << i << "] = " << ppArgv[i] << endl;
    }
    //cout << "******** end print ********" << endl;
}

/*****************************************************************************/
void CommandLine::BuildCommand(const char *CommandString)
/*****************************************************************************/
{
    int index = 0, pos=0;
    char buffer[1024];
    char WorkString[1024];

    strcpy(WorkString,CommandString);

    //falls LogWindow -> in tmpfile schreiben
    if(bTmpWrite)
    {
        strcpy(&WorkString[strlen(WorkString)]," >&");
        strcpy(&WorkString[strlen(WorkString)],getenv("TMP"));
        strcpy(&WorkString[strlen(WorkString)],TMPNAME);
    }

    // delete old memory and get some new memory for CommandBuffer

    delete [] CommandBuffer;
    CommandBuffer =  new char [strlen(ComShell)+strlen(WorkString)+1];
    if (CommandBuffer == NULL) {
        //cout << "Error: nospace" << endl;
        exit(0);
    }
    strcpy (CommandBuffer, ComShell);
    strcpy (&CommandBuffer[strlen(ComShell)], WorkString);

    CommandString = CommandBuffer;

    // get the number of tokens
    Strtokens(CommandString);

    // delete the space for the old CommandLine

    for (int i = 0; ppArgv[i] != 0; i++) {
        delete [] ppArgv[i];
    }
    delete [] ppArgv;

    /* get space for the new command line */

    ppArgv = (char **) new char * [nArgc+1];
    if (ppArgv == NULL) {
        //cout << "Error: no space" << endl;
        exit(0);
    }

    // flush the white space

    while ( isspace(*CommandString) )
        CommandString++;

    index = 0;

    // start the loop to build all the individual tokens

    while (*CommandString != '\0') {

        pos = 0;

        // copy the token until white space is found

        while ( !isspace(*CommandString) && *CommandString != '\0') {

            buffer[pos++] = *CommandString++;

        }

        buffer[pos] = '\0';

        // get space for the individual tokens

        ppArgv[index] = (char *) new char [strlen(buffer)+1];
        if (ppArgv[index] == NULL) {
            //cout << "Error: nospace" << endl;
            exit(0);
        }

        // copy the token

        strcpy (ppArgv[index++], buffer);

        // flush while space

        while ( isspace(*CommandString) )
            CommandString++;

    }

    // finish by setting the las pointer to NULL
    ppArgv[nArgc]= NULL;

}

/*****************************************************************************/
void CommandLine::Strtokens(const char *CommandString)
/*****************************************************************************/
{
    int count = 0;
    const char *temp;

    temp = CommandString;

    /* bypass white space */

    while (isspace(*temp)) temp++;

    for (count=0; *temp != '\0'; count++) {

        /* continue until white space of string terminator is found */

        while ((!isspace(*temp)) && (*temp != '\0')) temp++;

        /* bypass white space */

        while (isspace(*temp)) temp++;

    }
    nArgc = count;
}

/*****************************************************************************/
CCommand::CCommand( ByteString &rString )
/*****************************************************************************/
{
    rString.SearchAndReplace( '\t', ' ' );
    aCommand = rString.GetToken( 0, ' ' );
    aCommandLine = Search( "PATH" );
#ifndef UNX
    aCommandLine += " /c ";
#else
    aCommandLine += " -c ";
#endif

    ByteString sCmd( rString.GetToken( 0, ' ' ));
    ByteString sParam( rString.Copy( sCmd.Len()));

    aCommandLine += Search( "PATH", sCmd );
    aCommandLine += sParam;

    ImplInit();
}

/*****************************************************************************/
CCommand::CCommand( const char *pChar )
/*****************************************************************************/
{
    ByteString aString = pChar;
    aString.SearchAndReplace( '\t', ' ' );
    aCommand = aString.GetToken( 0, ' ' );

    aCommandLine = Search( "PATH" );
#ifndef UNX
    aCommandLine += " /c ";
#else
    aCommandLine += " -c ";
#endif
    ByteString rString( pChar );

    ByteString sCmd( rString.GetToken( 0, ' ' ));
    ByteString sParam( rString.Copy( sCmd.Len()));

    aCommandLine += Search( "PATH", sCmd );
    aCommandLine += sParam;

    ImplInit();
}

/*****************************************************************************/
void CCommand::ImplInit()
/*****************************************************************************/
{
    char pTmpStr[255];
    size_t *pPtr;
    char *pChar;
    int nVoid = sizeof( size_t * );
    nArgc = aCommandLine.GetTokenCount(' ');
    ULONG nLen = aCommandLine.Len();

    ppArgv = (char **) new char[ (ULONG)(nLen + nVoid * (nArgc +2) + nArgc ) ];
    pChar = (char *) ppArgv + ( (1+nArgc) * nVoid );
    pPtr = (size_t *) ppArgv;
    for ( xub_StrLen i=0; i<nArgc; i++ )
    {
        (void) strcpy( pTmpStr, aCommandLine.GetToken(i, ' ' ).GetBuffer() );
        size_t nStrLen = strlen( pTmpStr ) + 1;
        strcpy( pChar, pTmpStr );
        *pPtr = (sal_uIntPtr) pChar;
        pChar += nStrLen;
        pPtr += 1;
#ifdef UNX
        if ( i == 1 )
        {
            USHORT nWo = aCommandLine.Search("csh -c ");
            if (nWo != STRING_NOTFOUND)
                aCommandLine.Erase(0, nWo + 7);
            else
                aCommandLine.Erase(0, 16);
            i = nArgc;
            strcpy( pChar, aCommandLine.GetBuffer() );
            *pPtr = (sal_uIntPtr) pChar;
            pPtr += 1;
        }
#endif
    }
    *pPtr = 0;
}

/*****************************************************************************/
CCommand::operator int()
/*****************************************************************************/
{
    int nRet;
#if defined WNT
    nRet = _spawnv( P_WAIT, ppArgv[0], (const char **) ppArgv );
#elif defined OS2
    nRet = _spawnv( P_WAIT, ppArgv[0], ppArgv );
#elif defined UNX
    //fprintf( stderr, "CComand : operator (int) not implemented\n");
    // **** Unix Implementierung ***************
    pid_t pid;

    if (( pid = fork()) < 0 )
    {
        DBG_ASSERT( FALSE, "fork error" );
    }
    else if ( pid == 0 )
    {
        if ( execv( ppArgv[0], (char * const *) ppArgv ) < 0 )
        {
            DBG_ASSERT( FALSE, "execv failed" );
        }
    }
    //fprintf( stderr, "parent: %s %s\n", ppArgv[0] , ppArgv[1] );
    if ( (nRet = waitpid( pid, NULL, 0 ) < 0) )
    {
        DBG_ASSERT( FALSE, "wait error" );
    }
#endif

    switch ( errno )
    {
        case    E2BIG :
                    nError = COMMAND_TOOBIG;
                    break;
        case    EINVAL :
                    nError = COMMAND_INVALID;
                    break;
        case    ENOENT:
                    nError = COMMAND_NOTFOUND;
                    break;
        case    ENOEXEC :
                    nError = COMMAND_NOEXEC;
                    break;
        case    ENOMEM :
                    nError = COMMAND_NOMEM;
                    break;
        default:
                nError = COMMAND_UNKNOWN;
    }

    if ( nRet )
        fprintf( stderr, "Program returned with errros\n");
    return nRet;
}

/*****************************************************************************/
ByteString CCommand::Search(ByteString aEnv, ByteString sItem)
/*****************************************************************************/
{
    // default wird eine Shell im Path gesucht,
    // wenn aber compsec gestzt ist holen wir uns die
    // Shell von dort
    if ( sItem.Equals( COMMAND_SHELL ))
    {
        ByteString aComspec = GetEnv( "COMSPEC" );
        if ( !aComspec.Equals(""))
            return aComspec;
    }

    DirEntry aItem( String( sItem, RTL_TEXTENCODING_ASCII_US ));
    if ( aItem.Exists())
        return sItem;

    ByteString aEntry, sReturn;
    ByteString sEnv( aEnv );
    ByteString sEnvironment = GetEnv( sEnv.GetBuffer());
    xub_StrLen nCount = sEnvironment.GetTokenCount( cPathSeperator );

    BOOL bFound = FALSE;

    for ( xub_StrLen i=0; i<nCount && !bFound; i++ )
    {
        aEntry = sEnvironment.GetToken(i, cPathSeperator );
#ifndef UNX
        aEntry += '\\';
#else
        aEntry += '/';
#endif
        aEntry += sItem;

        String sEntry( aEntry, RTL_TEXTENCODING_ASCII_US );
        DirEntry aDirEntry( sEntry );
        aDirEntry.ToAbs();
        if ( aDirEntry.Exists()) {
            sReturn = aEntry;
            bFound = TRUE;
        }
    }
    if ( !bFound )
    {
        sEnv = sEnv.ToUpperAscii();
        ByteString sEnvironment2 = GetEnv(sEnv.GetBuffer() );
        xub_StrLen nCount2 = sEnvironment2.GetTokenCount( cPathSeperator );
        for ( xub_StrLen i=0; i<nCount2 && !bFound; i++ )
        {
            aEntry = sEnvironment2.GetToken(i, cPathSeperator );
#ifndef UNX
            aEntry += '\\';
#else
            aEntry += '/';
#endif
            aEntry += sItem;

            String sEntry( aEntry, RTL_TEXTENCODING_ASCII_US );
            DirEntry aDirEntry( sEntry );
            aDirEntry.ToAbs();
            if ( aDirEntry.Exists()) {
                sReturn = aEntry;
                bFound = TRUE;
            }
        }
    }

    if ( sReturn.Equals( "" ))
        sReturn = sItem;

    return sReturn;
}

/*****************************************************************************/
CCommandd::CCommandd( ByteString &rString, CommandBits nBits )
/*****************************************************************************/
                : CCommand( rString ),
                nFlag( nBits )
{
}


/*****************************************************************************/
CCommandd::CCommandd( const char *pChar, CommandBits nBits )
/*****************************************************************************/
                : CCommand( pChar ),
                nFlag( nBits )
{
}

/*****************************************************************************/
CCommandd::operator int()
/*****************************************************************************/
{
    int nRet = 0;

#ifdef WNT
    LPCTSTR lpApplicationName = NULL;
    LPTSTR lpCommandLine = (char *) GetCommandLine_().GetBuffer();
    LPSECURITY_ATTRIBUTES lpProcessAttributes = NULL;
    LPSECURITY_ATTRIBUTES lpThreadAttributes = NULL;
    BOOL bInheritHandles = TRUE;

    // wie wuenschen wir denn gestartet zu werden ??
    DWORD dwCreationFlags;

    if ( nFlag & COMMAND_EXECUTE_START )
        dwCreationFlags = DETACHED_PROCESS;
    else
        dwCreationFlags = CREATE_NEW_CONSOLE;

    // wir erben vom Vaterprozess
    LPVOID lpEnvironment = NULL;

    // das exe im Pfad suchen
    LPCTSTR lpCurrentDirectory = NULL;

    // in dieser Struktur bekommen wir die erzeugte Processinfo
    // zurueck
    PROCESS_INFORMATION aProcessInformation;

    // weiteres Startupinfo anlegen
    STARTUPINFO aStartupInfo;

    aStartupInfo.cb = sizeof( STARTUPINFO );
    aStartupInfo.lpReserved = NULL;
    aStartupInfo.lpDesktop = NULL;

    // das Fenster bekommt den Namen des Exes
    aStartupInfo.lpTitle = NULL;
    aStartupInfo.dwX = 100;
    aStartupInfo.dwY = 100;
    //aStartupInfo.dwXSize = 400;
    //aStartupInfo.dwYSize = 400;
    aStartupInfo.dwXCountChars = 40;
    aStartupInfo.dwYCountChars = 40;

    // Farben setzen
    aStartupInfo.dwFillAttribute = FOREGROUND_RED | BACKGROUND_RED |
                                BACKGROUND_BLUE | BACKGROUND_GREEN;

//  aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
    //aStartupInfo.wShowWindow = SW_NORMAL; //SW_SHOWDEFAULT;
    //aStartupInfo.wShowWindow = SW_HIDE; //SW_SHOWNOACTIVATE;
    aStartupInfo.wShowWindow = SW_SHOWNOACTIVATE;
    aStartupInfo.cbReserved2 = NULL;
    aStartupInfo.lpReserved2 = NULL;
    //aStartupInfo.hStdInput = stdin;
    //aStartupInfo.hStdOutput = stdout;
    //aStartupInfo.hStdError = stderr;

    if ( nFlag & COMMAND_EXECUTE_HIDDEN )
    {
        aStartupInfo.wShowWindow = SW_HIDE;
        aStartupInfo.dwFlags = aStartupInfo.dwFlags | STARTF_USESHOWWINDOW;
    }

    bool bProcess = CreateProcess( lpApplicationName,
                        lpCommandLine, lpProcessAttributes,
                        lpThreadAttributes, bInheritHandles,
                        dwCreationFlags, lpEnvironment, lpCurrentDirectory,
                        &aStartupInfo, &aProcessInformation );

    LPVOID lpMsgBuf;

    if ( bProcess )
    {
        FormatMessage(
                FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
                NULL,
                GetLastError(),
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                (LPTSTR) &lpMsgBuf,
                0,
                NULL );

        ByteString aErrorString = (char *) lpMsgBuf;

        if ( nFlag & COMMAND_EXECUTE_WAIT )
        {
            DWORD aProcessState = STILL_ACTIVE;
            while(aProcessState == STILL_ACTIVE)
            {
                GetExitCodeProcess(aProcessInformation.hProcess,&aProcessState);
            }
        }
    }
    else
        fprintf( stderr, "Can not start Process !" );

#endif
    return nRet;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */