aboutsummaryrefslogtreecommitdiff
path: root/tools/mhmake/src/util.cpp
blob: 9fe006e95d28304e31bb6b86c3866891839f651a (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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
/*  This file is part of mhmake.
 *
 *  Copyright (C) 2001-2010 marha@sourceforge.net
 *
 *  Mhmake is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Mhmake 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Mhmake.  If not, see <http://www.gnu.org/licenses/>.
*/

/* $Rev$ */

#include "stdafx.h"

#include "rule.h"
#include "util.h"
#include "mhmakeparser.hpp"

#ifdef WIN32

#include <WinIoCtl.h>

#define REPARSE_MOUNTPOINT_HEADER_SIZE   8

typedef struct {
  DWORD ReparseTag;
  DWORD ReparseDataLength;
  WORD Reserved;
  WORD ReparseTargetLength;
  WORD ReparseTargetMaximumLength;
  WORD Reserved1;
  WCHAR ReparseTarget[1];
} REPARSE_MOUNTPOINT_DATA_BUFFER, *PREPARSE_MOUNTPOINT_DATA_BUFFER;
#endif

static char s_UsageString[]=
"\
Usage: mhmake [-f <Makefile>] [-[c|C] <RunDir>] [<Var>=<Value>]\n\
              [-a] [-q] [-s] [-S] [-v] [-P <Nr Parallel Builds>] [targets]+\n"
#ifdef _DEBUG
"\
              [-p] [-n] [-e] [-l] [-w] [-d] [-CD] [-m] [-b]\n"
#endif
"\n\
  <Makefile>  : Makefile to load (if not specified 'makefile' is used\n\
  <RunDir>    : Make is setting the current directory to this directory at the\n\
                start.\n\
  <Var>       : Defines a variable\n\
  <Value>     : Value of the variable\n\
  -a          : Rebuild all targets\n\
  -s          : Rescan automatic dependencies\n\
  -S          : SKip checking if mhmake is started in a subdirectory of the\n\
                %MHMAKECONF dir \n\
  -v          : Print version information\n\
  -q          : Quiet. Disable all output \n\
  -P <Nr Parallel Builds> :\n\
                Number of parallel build commands executed at the \n\
                same time. Default is this the number of processor \n\
                cores. 1 disables parallel builds.\n"
#ifdef _DEBUG
"\n\
  The following options are additional options in mhmake_dbg which are not\n\
  available in mhmake. These are mainly options for debugging purposes.\n\
  -e          : Dump Vars and Rules on error\n\
  -w          : Print additional information\n\
  -p          : Prints the variables and the rules before building\n\
  -n          : Only prints the commands, but does not execute them\n\
  -l          : Print parser debug information\n\
  -d          : Print the dependency checking\n\
  -CD         : Do circular dependency checking (targets depending on itself)\n\
  -m          : Create md5 database in md5.database in start directory. \n\
  -b          : Print build tree. \n\
  -D          : Print all double defined rules (even if commands are the same) \n\
"
#else
"\
\n\
It is adviced during creation of makefiles to use mhmake_dbg. It has additional\n\
debugging options and does some extra error checking.\n\
For a description of the additional options: run mhmake_dbg -h\n\
"
#endif
;

#ifdef _DEBUG
bool g_PrintVarsAndRules=false;
bool g_DoNotExecute=false;
bool g_BuildMd5Db=false;
bool g_GenProjectTree=false;
bool g_DumpOnError=false;
bool g_PrintAdditionalInfo=false;
bool g_pPrintDependencyCheck=false;
bool g_CheckCircularDeps=false;
bool g_PrintLexYacc=false;
bool g_PrintMultipleDefinedRules=false;
#endif

bool g_Quiet=false;
bool g_RebuildAll=false;
bool g_ForceAutoDepRescan=false;
bool g_SkipMhMakeConfDirCheck=false;

const string g_EmptyString;
const string g_SpaceString(" ");

///////////////////////////////////////////////////////////////////////////////
void PrintVersionInfo(void)
{
  static const char VersionStr[]="\
mhmake : GNU compatible make tool with extensions\n\
version: "MHMAKEVER"\n\
Remarks and bug reports -> marha@sourceforge.net\n\
";
  cerr << VersionStr;
  exit(1);
}
///////////////////////////////////////////////////////////////////////////////
makecommand::makecommand()
{
  char ExeName[MAX_PATH];
#ifdef WIN32
  GetModuleFileName(NULL,ExeName,sizeof(ExeName));
  m_BuildCommand=ExeName;
  transform(m_BuildCommand.begin(),m_BuildCommand.end(),m_BuildCommand.begin(),(int(__CDECL *)(int))tolower);
#else
  int NrChars=readlink ("/proc/self/exe", ExeName, sizeof(ExeName));
  ExeName[NrChars]=0;
  m_BuildCommand=ExeName;
#endif
}

///////////////////////////////////////////////////////////////////////////////
string Substitute(const string &ToSubst,const string &iSrcStr,const string &iToStr)
{
  string Ret=g_EmptyString;
  matchres Res;
  string SrcStr=iSrcStr;
  string ToStr=iToStr;

  if (string::npos==SrcStr.find('%'))
  {
    string PerStr("%");
    SrcStr=PerStr+SrcStr;
    ToStr=PerStr+ToStr;
  }
  const char *pTmp=ToSubst.c_str();
  bool first=true;
  while (*pTmp)
  {
    if (!first)
    {
      Ret+=g_SpaceString;
    }
    else
    {
      first=false;
    }
    string Item;
    pTmp=NextItem(pTmp,Item);

    if (PercentMatch(Item,SrcStr,&Res))
    {
      Ret+=ReplaceWithStem(ToStr,Res.m_Stem);
    }
    else
    {
      Ret+=Item;
    }
  }

  return Ret;
}

///////////////////////////////////////////////////////////////////////////////
bool PercentMatch(const string &String,const string &Expr,matchres *pRes,const char Char)
{
  const char *pFirst=String.c_str();
  const char *pFirstExpr=Expr.c_str();
  while (*pFirstExpr && *pFirstExpr!=Char)
  {
    if (*pFirst!=*pFirstExpr)
      return false;
    pFirst++;
    pFirstExpr++;
  }

  if (!*pFirstExpr)
  {
    if (!*pFirst)
    {
      if (pRes)
      {
        pRes->m_First=String;
        pRes->m_Stem=pRes->m_Last=g_EmptyString;
      }
      return true;
    } else
      return false;
  }
  else if (!*pFirst)
    return false;

  const char *pEnd=pFirst+strlen(pFirst);

  const char *pLast=pEnd;
  const char *pLastExpr=pFirstExpr+strlen(pFirstExpr)-1;
  if (pLastExpr!=pFirstExpr)
  {
    pLast--;

    while (pLastExpr>pFirstExpr)
    {
      if (*pLastExpr!=*pLast)
        return false;
      pLastExpr--;
      pLast--;
    }
    pLast++;
  }
  string Stem=string(pFirst,pLast-pFirst);

  if (pRes)
  {
    pRes->m_First=string(String.c_str(),pFirst-String.c_str());

    pRes->m_Stem=Stem;

    pRes->m_Last=string(pLast,pEnd-pLast);
  }
  return true;
}
///////////////////////////////////////////////////////////////////////////////
bool PercentMatchNoCase(const string &String,const string &Expr,matchres *pRes,const char Char)
{
  const char *pFirst=String.c_str();
  const char *pFirstExpr=Expr.c_str();
  while (*pFirstExpr && *pFirstExpr!=Char)
  {
    if (tolower(*pFirst)!=tolower(*pFirstExpr))
      return false;
    pFirst++;
    pFirstExpr++;
  }

  if (!*pFirstExpr)
  {
    if (!*pFirst)
    {
      if (pRes)
      {
        pRes->m_First=String;
        pRes->m_Stem=pRes->m_Last=g_EmptyString;
      }
      return true;
    } else
      return false;
  }
  else if (!*pFirst)
    return false;

  const char *pEnd=pFirst+strlen(pFirst);

  const char *pLast=pEnd;
  const char *pLastExpr=pFirstExpr+strlen(pFirstExpr)-1;
  if (pLastExpr!=pFirstExpr)
  {
    pLast--;

    while (pLastExpr>pFirstExpr)
    {
      if (tolower(*pLastExpr)!=tolower(*pLast))
        return false;
      pLastExpr--;
      pLast--;
    }
    pLast++;
  }
  string Stem=string(pFirst,pLast-pFirst);

  if (pRes)
  {
    pRes->m_First=string(String.c_str(),pFirst-String.c_str());

    pRes->m_Stem=Stem;

    pRes->m_Last=string(pLast,pEnd-pLast);
  }
  return true;
}
///////////////////////////////////////////////////////////////////////////////
bool PercentMatchList(const string &String,const string &ExprList,matchres *pRes)
{
  const char *pTmp=ExprList.c_str();
  while (*pTmp)
  {
    string Expr;
    pTmp=NextItem(pTmp,Expr);
    if (PercentMatch(String,Expr,pRes))
      return true;
  }
  return false;
}

///////////////////////////////////////////////////////////////////////////////
string ReplaceWithStem(const string &String,const string &Stem)
{
  string Ret=String;
  size_t Pos=Ret.find('%');
  while (Pos!=string::npos)
  {
    Ret=Ret.substr(0,Pos)+Stem+Ret.substr(Pos+1);
    Pos=Ret.find('%');
  }
  return Ret;
}

///////////////////////////////////////////////////////////////////////////////
refptr<loadedmakefile> LOADEDMAKEFILES::find(const loadedmakefile &ToSearch)
{
  vector<refptr<loadedmakefile> >::const_iterator It=begin();
  while (It!=end())
  {
    if (*(*It)==ToSearch)
      return *It;
    It++;
  }
  return refptr<loadedmakefile>();
}

LOADEDMAKEFILES g_LoadedMakefiles;

///////////////////////////////////////////////////////////////////////////////
loadedmakefile::loadedmakefile_statics::loadedmakefile_statics()
{
  m_GlobalCommandLineVars[MAKE]=g_MakeCommand;
  const char *pEnv=getenv(MHMAKECONF);
  if (pEnv)
  {
    m_MhMakeConf=GetAbsFileInfo(pEnv);
    m_GlobalCommandLineVars[MHMAKECONF]=QuoteFileName(m_MhMakeConf->GetFullFileName());

    // Get the revision of the working copy
    // We do it with the svn info command

    string Output;
    try
    {
      mhmakefileparser Dummy(curdir::GetCurDir());
      string SvnCommand=Dummy.SearchCommand("svn",EXEEXT);
      #ifdef WIN32
      if (GetFileAttributes(m_MhMakeConf->GetFullFileName().c_str())&FILE_ATTRIBUTE_REPARSE_POINT)
      {
        WIN32_FIND_DATA FindData;
        HANDLE hFind=FindFirstFile(m_MhMakeConf->GetFullFileName().c_str(),&FindData);
        if (hFind!=INVALID_HANDLE_VALUE)
        {
          if (FindData.dwReserved0==IO_REPARSE_TAG_MOUNT_POINT)
          {
            HANDLE hDir = ::CreateFile(m_MhMakeConf->GetFullFileName().c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, NULL);

            BYTE buf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];  // We need a large buffer
            REPARSE_MOUNTPOINT_DATA_BUFFER& ReparseBuffer = (REPARSE_MOUNTPOINT_DATA_BUFFER&)buf;
            DWORD dwRet;

            if (::DeviceIoControl(hDir, FSCTL_GET_REPARSE_POINT, NULL, 0, &ReparseBuffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &dwRet, NULL))
            {
              // Success
              ::CloseHandle(hDir);

              LPCWSTR pPath = ReparseBuffer.ReparseTarget;
              if (wcsncmp(pPath, L"\\??\\", 4) == 0) pPath += 4;  // Skip 'non-parsed' prefix
              char szPath[MAX_PATH];
              ::WideCharToMultiByte(CP_ACP, 0, pPath, -1, szPath, MAX_PATH, NULL, NULL);
              Dummy.OsExeCommand(SvnCommand,string(" info ")+GetFileInfo(szPath,m_MhMakeConf->GetDir())->GetQuotedFullFileName(),false,&Output);
            }
            else
            {  // Error
              ::CloseHandle(hDir);
            }
          }
          FindClose(hFind);
        }
      }
      #else
      struct stat Stat;
      lstat(m_MhMakeConf->GetFullFileName().c_str(),&Stat);
      if (S_ISLNK(Stat.st_mode))
      {
        char FileName[1024];
        int len=readlink(m_MhMakeConf->GetFullFileName().c_str(),FileName,sizeof(FileName));
        FileName[len]=0;
        Dummy.OsExeCommand(SvnCommand,string(" info ")+GetFileInfo(FileName,m_MhMakeConf->GetDir())->GetQuotedFullFileName(),false,&Output);
      }
      #endif
      else
        Dummy.OsExeCommand(SvnCommand,string(" info ")+m_MhMakeConf->GetQuotedFullFileName(),false,&Output);
    }
    catch (string Message)
    {
    }

    char *pTok=strtok((char*)Output.c_str(),"\n");   // doing this is changing string, so this is very dangerous !!!
    while (pTok)
    {
      if (!strncmp(pTok,"URL: ",5))
      {
        m_GlobalCommandLineVars[WC_URL]=pTok+5+7;
      }
      else if (!strncmp(pTok,"Revision: ",10))
      {
        m_GlobalCommandLineVars[WC_REVISION]=pTok+10;
        break;
      }
      pTok=strtok(NULL,"\n");
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
loadedmakefile::loadedmakefile(const fileinfo *pDir, vector<string> &Args,const string&Makefile)
{
  m_Makefile=NULL;
  m_CommandLineVars=sm_Statics.m_GlobalCommandLineVars;

  m_MakeDir=NULL;
  vector<string>::iterator ArgIt=Args.begin();
  while (ArgIt!=Args.end())
  {
    size_t EqPos=ArgIt->find('=');
    if (EqPos!=string::npos)
    {
      string Var=ArgIt->substr(0,EqPos);
      string Val=ArgIt->substr(EqPos+1);
      m_CommandLineVars[Var]=Val;
    }
    else if ((*ArgIt)[0]=='-')
    {
      switch ((*ArgIt)[1])
      {
        case 'f':
          if (ArgIt->size()>2)
          {
            if (!m_MakeDir)
            {
              m_Makefile=GetFileInfo(ArgIt->substr(2),pDir);
            }
            else
            {
              m_Makefile=GetFileInfo(ArgIt->substr(2),m_MakeDir);
            }
          }
          else
          {
            ArgIt++;
            if (!m_MakeDir)
            {
              m_Makefile=GetFileInfo(*ArgIt,pDir);
            }
            else
            {
              m_Makefile=GetFileInfo(*ArgIt,m_MakeDir);
            }
          }
          break;
        case 'C':
#ifdef _DEBUG
          if (ArgIt->size()>2 && (*ArgIt)[2]=='D')
          {
            g_CheckCircularDeps=true;
            break;
          }
#endif
          /* Fall through */
        case 'c':
          if (ArgIt->size()>2)
            m_MakeDir=GetFileInfo(ArgIt->substr(2),pDir);
          else
          {
            ArgIt++;
            m_MakeDir=GetFileInfo(*ArgIt,pDir);
          }
          break;
        case 'a':
          g_RebuildAll=true;
          break;
        case 'q':
          g_Quiet=true;
          break;
        case 's':
          g_ForceAutoDepRescan=true;
          break;
        case 'S':
          g_SkipMhMakeConfDirCheck=true;
          break;
        case 'v':
          PrintVersionInfo();
          break;
        case 'P':
          if (ArgIt->size()>2)
            mhmakefileparser::SetNrParallelBuilds(atoi(ArgIt->substr(2).c_str()));
          else
          {
            ArgIt++;
            mhmakefileparser::SetNrParallelBuilds(atoi((*ArgIt).c_str()));
          }
          break;
#ifdef _DEBUG
        case 'p':
          g_PrintVarsAndRules=true;
          break;
        case 'n':
          g_DoNotExecute=true;
          break;
        case 'w':
          g_PrintAdditionalInfo=true;
          break;
        case 'd':
          g_pPrintDependencyCheck=true;
          break;
        case 'D':
          g_PrintMultipleDefinedRules=true;
          break;
        case 'l':
          g_PrintLexYacc=true;
          break;
        case 'e':
          g_DumpOnError=true;
          break;
        case 'm':
          g_BuildMd5Db=true;
          break;
        case 'b':
          g_GenProjectTree=true;
          break;
#endif
        default:
          throw string("\nUnknown option: ")+*ArgIt+"\n\n"+ s_UsageString;
      }
    }
    else
    {
      m_CommandLineTargets.push_back(*ArgIt);
    }
    ArgIt++;
  }
  if (!m_Makefile)
  {
    if (!Makefile.empty())
    {
      if (!m_MakeDir)
        m_Makefile=GetFileInfo(Makefile,pDir);
      else
        m_Makefile=GetFileInfo(Makefile,m_MakeDir);
    }
  }
  if (!m_Makefile)
  {
    if (!m_MakeDir)
      m_Makefile=GetFileInfo(m_CommandLineTargets[0],pDir);
    else
      m_Makefile=GetFileInfo(m_CommandLineTargets[0],m_MakeDir);

    m_CommandLineTargets.erase(m_CommandLineTargets.begin());
  }
  if (!m_MakeDir)
  {
    if (Makefile==g_EmptyString)
      m_MakeDir=m_Makefile->GetDir(); /* This  is one from load_makefile, so we take the directory of the makefile itself. */
    else
      m_MakeDir=curdir::GetCurDir(); /* This means that this is the main makefile given on the command line, so we take the current directory */
  }

  if (!g_SkipMhMakeConfDirCheck)
  {
    if (loadedmakefile::sm_Statics.m_MhMakeConf)
    {
      const string &RootDir=loadedmakefile::sm_Statics.m_MhMakeConf->GetFullFileName();
      string MakeDir=m_MakeDir->GetFullFileName();
      if (RootDir.length()>MakeDir.length() || strncmp(RootDir.c_str(),MakeDir.c_str(),RootDir.length()))
      {
        cerr<<"mhmake needs to run in a directory that is a subdirectory of the directory specified with %MHMAKECONF : "<<RootDir<<", make dir : "<<m_MakeDir->GetFullFileName()<<"\nComparison is case sensitive!\n";
        exit(1);
      }
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
void loadedmakefile::LoadMakefile()
{
  #ifdef _DEBUG
  if (g_PrintAdditionalInfo)
    cout << "Loading makefile "<<m_Makefile->GetQuotedFullFileName()<<endl;
  #endif

  m_pMakefileParser=refptr<mhmakefileparser>(new mhmakefileparser(m_CommandLineVars));

  // Add the MAKECMDGOALS environment variable
  string MakeCmdGoals;
  bool First=true;
  vector<string>::iterator TarIt=m_CommandLineTargets.begin();
  while (TarIt!=m_CommandLineTargets.end())
  {
    if (First)
      First=false;
    else
      MakeCmdGoals+=g_SpaceString;
    MakeCmdGoals+=*TarIt;
    TarIt++;
  }
  m_pMakefileParser->SetVariable("MAKECMDGOALS",MakeCmdGoals);

  string BaseAutoMak;

  // First parse the makefile.before makefile which is in the directory $(MHMAKECONF) environment variable
  fileinfo *pDepFile;
  if (sm_Statics.m_MhMakeConf)
  {
    BaseAutoMak=m_pMakefileParser->ExpandVar(BASEAUTOMAK);
    if (BaseAutoMak.empty())
    {
      BaseAutoMak="makefile";
      m_pMakefileParser->SetVariable(BASEAUTOMAK,BaseAutoMak);
    }
    const fileinfo *pBeforeMakefile=GetFileInfo(BaseAutoMak+".before",sm_Statics.m_MhMakeConf);

    int result=m_pMakefileParser->ParseFile(pBeforeMakefile,m_MakeDir);
    if (result)
    {
      throw string("Error parsing ")+pBeforeMakefile->GetQuotedFullFileName();
    }
    m_pMakefileParser->UpdateDate(pBeforeMakefile->GetDate());

    // Now parse the automaticly generated dependency file, which needs to be in the objdir directory
    string ObjDirName=m_pMakefileParser->ExpandExpression("$(OBJDIR)");
    if (!ObjDirName.size())
    {
      throw string("When making use of MHMAKECONF, you have to define OBJDIR in makefile.before");
    }
    pDepFile=GetFileInfo(ObjDirName+OSPATHSEPSTR "." + m_Makefile->GetName()+ ".dep",m_MakeDir);
    m_pMakefileParser->SetVariable(AUTODEPFILE,pDepFile->GetQuotedFullFileName());
  }
  else
  {
    pDepFile=GetFileInfo(string(".") + m_Makefile->GetName()+ ".dep",m_MakeDir);
    m_pMakefileParser->SetVariable(AUTODEPFILE,pDepFile->GetQuotedFullFileName());
  }

  if (pDepFile->Exists())
    m_pMakefileParser->LoadAutoDepsFile(pDepFile); /* Already load this autodep file before parsing of the makefile to avoid needless rebuilds. */

  //m_pMakefileParser->yydebug=1;
  int result=m_pMakefileParser->ParseFile(m_Makefile,m_MakeDir);
  if (result)
  {
    throw string("Error parsing ")+m_Makefile->GetQuotedFullFileName();
  }

  fileinfo *pMaybeNewDepFile=GetFileInfo(m_pMakefileParser->ExpandVar(AUTODEPFILE),m_MakeDir);
  #ifdef _DEBUG
  /* Check if the makefile has changed the AUTODEPFILE variable, if so generate a warning that a
   * rebuild could happen for the rules defined for making included makefiles */
  if (pMaybeNewDepFile!=pDepFile)
  {
    cout << "\n\nWARNING:\n  makefile '"<< m_Makefile->GetQuotedFullFileName() <<"' re-defines AUTODEPFILE\n  from '"<< pDepFile->GetQuotedFullFileName() <<"'\n  to '"<<
            m_pMakefileParser->ExpandVar(AUTODEPFILE) << "'\n  (may cause needless rebuilds when having rules for included makefiles!!!!!)\n\n\n";
  }

  if (g_PrintAdditionalInfo)
  {
    if (m_pMakefileParser->GetFirstTarget())
      cout<<"First target of "<<m_Makefile->GetQuotedFullFileName()<<" is "<<m_pMakefileParser->GetFirstTarget()->GetQuotedFullFileName()<<endl;
    else
      cout<<"No First target for "<<m_Makefile->GetQuotedFullFileName()<<endl;
  }
  #endif

  if (pMaybeNewDepFile!=pDepFile)
  {
    // this means the makefile has overruled the AUTODEPFILE, so parse it again
    pDepFile=pMaybeNewDepFile;
    if (pDepFile->Exists())
      m_pMakefileParser->LoadAutoDepsFile(pDepFile); /* If it already exists, load it. */
  }

  m_pMakefileParser->UpdateDate(m_Makefile->GetDate());

  if (sm_Statics.m_MhMakeConf)
  {
    fileinfo  *pAfterMakefile=GetFileInfo(BaseAutoMak+".after",sm_Statics.m_MhMakeConf);
    int result=m_pMakefileParser->ParseFile(pAfterMakefile);
    if (result) {
      throw string("Error parsing ")+pAfterMakefile->GetQuotedFullFileName();
    }
    m_pMakefileParser->UpdateDate(pAfterMakefile->GetDate());
  }
  bool ForceAutoDepRescan=g_ForceAutoDepRescan;
  if (pDepFile->Exists())
    m_pMakefileParser->LoadAutoDepsFile(pDepFile);
  else
    ForceAutoDepRescan=true;
  if (ForceAutoDepRescan)
    m_pMakefileParser->EnableAutoDepRescan();

  vector<string> &MakefilesToLoad=m_pMakefileParser->GetMakefilesToLoad();
  vector<string>::iterator It=MakefilesToLoad.begin();
  while (It!=MakefilesToLoad.end())
  {
    // First split the command into arguments
    const char *pTmp=It->c_str();
    vector<string> Args;
    while (*pTmp)
    {
      string Item;
      pTmp=NextItem(pTmp,Item);
      Args.push_back(Item);
    }

    refptr<loadedmakefile> pLoadedMakefile(new loadedmakefile(m_MakeDir,Args));
    refptr<loadedmakefile> Found=g_LoadedMakefiles.find(*pLoadedMakefile);
    if (Found)
    {
      #ifdef _DEBUG
      if (g_PrintAdditionalInfo)
        cout << "Makefile already loaded: "<<Found->m_Makefile->GetQuotedFullFileName()<<endl;
      #endif
    }
    else
    {
      g_LoadedMakefiles.push_back(pLoadedMakefile);

        /* If there is a rule to build the makefile, first check if it needs to be rebuild */
      m_pMakefileParser->BuildTarget(pLoadedMakefile->m_Makefile);
      pLoadedMakefile->LoadMakefile();
    }
    It++;
  }
}

/*****************************************************************************/
bool MakeDirs(fileinfo *pDir)
{
  fileinfo *pParentDir=pDir->GetDir();
  if (!pParentDir->GetDate().DoesExist())
  {  /* First make parent dirs */
    if (!MakeDirs(pParentDir))
      return false;
  }
  if (!pDir->GetDate().DoesExist())
  { /* Create directory */
    struct stat statbuf;
    if ( (-1==stat(pParentDir->GetFullFileName().c_str(),&statbuf)) ||
         (-1==mkdir(pDir->GetFullFileName().c_str(),statbuf.st_mode))
       )
    {
      cerr << "mkdir function failed for directory " << QuoteFileName(pDir->GetFullFileName()) << endl;
      return false;
    }
    pDir->InvalidateDate(); // Directory created successfully, so invalidate the date
  }
  return true;
}

#ifdef _DEBUG
///////////////////////////////////////////////////////////////////////////////
void DumpVarsAndRules()
{
  int i;
  LOADEDMAKEFILES::iterator LoadMakIt=g_LoadedMakefiles.begin();
  while (LoadMakIt!=g_LoadedMakefiles.end())
  {
    for (i=0; i<80; i++) cout << "_";
    cout << endl;
    cout << "Variables of makefile " << (*LoadMakIt)->m_Makefile->GetQuotedFullFileName() << endl;
    for (i=0; i<80; i++) cout << "_";
    cout << endl;
    (*LoadMakIt)->m_pMakefileParser->PrintVariables(true);
    cout << endl;
    LoadMakIt++;
  }
  for (i=0; i<80; i++) cout << "_";
  cout << endl;
  cout << "All Rules\n";
  for (i=0; i<80; i++) cout << "_";
  cout << endl;
  PrintFileInfos();
  for (i=0; i<80; i++) cout << "_";
  cout << endl;
  cout << "All Implicit Rules\n";
  for (i=0; i<80; i++) cout << "_";
  cout << endl;
  IMPLICITRULE::PrintImplicitRules();
}
#endif