3025a5cefe699ad38469a38984ee57cd3e3a9003
[profile/ivi/qtbase.git] / qmake / generators / makefile.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the qmake application of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "makefile.h"
43 #include "option.h"
44 #include "cachekeys.h"
45 #include "meta.h"
46 #include <qdir.h>
47 #include <qfile.h>
48 #include <qtextstream.h>
49 #include <qregexp.h>
50 #include <qhash.h>
51 #include <qdebug.h>
52 #include <qbuffer.h>
53 #include <qsettings.h>
54 #include <qdatetime.h>
55 #if defined(Q_OS_UNIX)
56 #include <unistd.h>
57 #else
58 #include <io.h>
59 #endif
60 #include <qdebug.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <time.h>
64 #include <fcntl.h>
65 #include <sys/types.h>
66 #include <sys/stat.h>
67
68 QT_BEGIN_NAMESPACE
69
70 // Well, Windows doesn't have this, so here's the macro
71 #ifndef S_ISDIR
72 #  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
73 #endif
74
75 bool MakefileGenerator::canExecute(const QStringList &cmdline, int *a) const
76 {
77     int argv0 = -1;
78     for(int i = 0; i < cmdline.count(); ++i) {
79         if(!cmdline.at(i).contains('=')) {
80             argv0 = i;
81             break;
82         }
83     }
84     if(a)
85         *a = argv0;
86     if(argv0 != -1) {
87         const QString c = Option::fixPathToLocalOS(cmdline.at(argv0), true);
88         if(exists(c))
89             return true;
90     }
91     return false;
92 }
93
94 QString MakefileGenerator::mkdir_p_asstring(const QString &dir, bool escape) const
95 {
96     QString ret =  "@" + chkdir + " ";
97     if(escape)
98         ret += escapeFilePath(dir);
99     else
100         ret += dir;
101     ret += " " + chkglue + "$(MKDIR) ";
102     if(escape)
103         ret += escapeFilePath(dir);
104     else
105         ret += dir;
106     ret += " ";
107     return ret;
108 }
109
110 bool MakefileGenerator::mkdir(const QString &in_path) const
111 {
112     QString path = Option::fixPathToLocalOS(in_path);
113     if(QFile::exists(path))
114         return true;
115
116     QDir d;
117     if(path.startsWith(QDir::separator())) {
118         d.cd(QString(QDir::separator()));
119         path.remove(0, 1);
120     }
121     bool ret = true;
122 #ifdef Q_OS_WIN
123     bool driveExists = true;
124     if(!QDir::isRelativePath(path)) {
125         if(QFile::exists(path.left(3))) {
126             d.cd(path.left(3));
127             path.remove(0, 3);
128         } else {
129             warn_msg(WarnLogic, "Cannot access drive '%s' (%s)",
130                      path.left(3).toLatin1().data(), path.toLatin1().data());
131             driveExists = false;
132         }
133     }
134     if(driveExists)
135 #endif
136     {
137         QStringList subs = path.split(QDir::separator());
138         for(QStringList::Iterator subit = subs.begin(); subit != subs.end(); ++subit) {
139             if(!d.cd(*subit)) {
140                 d.mkdir((*subit));
141                 if(d.exists((*subit))) {
142                     d.cd((*subit));
143                 } else {
144                     ret = false;
145                     break;
146                 }
147             }
148         }
149     }
150     return ret;
151 }
152
153 // ** base makefile generator
154 MakefileGenerator::MakefileGenerator() :
155     init_opath_already(false), init_already(false), no_io(false), project(0)
156 {
157 }
158
159
160 void
161 MakefileGenerator::verifyCompilers()
162 {
163     QHash<QString, QStringList> &v = project->variables();
164     QStringList &quc = v["QMAKE_EXTRA_COMPILERS"];
165     for(int i = 0; i < quc.size(); ) {
166         bool error = false;
167         QString comp = quc.at(i);
168         if(v[comp + ".output"].isEmpty()) {
169             if(!v[comp + ".output_function"].isEmpty()) {
170                 v[comp + ".output"].append("${QMAKE_FUNC_FILE_IN_" + v[comp + ".output_function"].first() + "}");
171             } else {
172                 error = true;
173                 warn_msg(WarnLogic, "Compiler: %s: No output file specified", comp.toLatin1().constData());
174             }
175         } else if(v[comp + ".input"].isEmpty()) {
176             error = true;
177             warn_msg(WarnLogic, "Compiler: %s: No input variable specified", comp.toLatin1().constData());
178         }
179         if(error)
180             quc.removeAt(i);
181         else
182             ++i;
183     }
184 }
185
186 void
187 MakefileGenerator::initOutPaths()
188 {
189     if(init_opath_already)
190         return;
191     verifyCompilers();
192     init_opath_already = true;
193     QHash<QString, QStringList> &v = project->variables();
194     //for shadow builds
195     if(!v.contains("QMAKE_ABSOLUTE_SOURCE_PATH")) {
196         if (Option::mkfile::do_cache && !project->cacheFile().isEmpty() &&
197            v.contains("QMAKE_ABSOLUTE_SOURCE_ROOT")) {
198             QString root = v["QMAKE_ABSOLUTE_SOURCE_ROOT"].first();
199             root = QDir::fromNativeSeparators(root);
200             if(!root.isEmpty()) {
201                 QFileInfo fi = fileInfo(project->cacheFile());
202                 if(!fi.makeAbsolute()) {
203                     QString cache_r = fi.path(), pwd = Option::output_dir;
204                     if(pwd.startsWith(cache_r) && !pwd.startsWith(root)) {
205                         pwd = root + pwd.mid(cache_r.length());
206                         if(exists(pwd))
207                             v.insert("QMAKE_ABSOLUTE_SOURCE_PATH", QStringList(pwd));
208                     }
209                 }
210             }
211         }
212     }
213     if(!v["QMAKE_ABSOLUTE_SOURCE_PATH"].isEmpty()) {
214         QString &asp = v["QMAKE_ABSOLUTE_SOURCE_PATH"].first();
215         asp = QDir::fromNativeSeparators(asp);
216         if(asp.isEmpty() || asp == Option::output_dir) //if they're the same, why bother?
217             v["QMAKE_ABSOLUTE_SOURCE_PATH"].clear();
218     }
219
220     QString currentDir = qmake_getpwd(); //just to go back to
221
222     //some builtin directories
223     if(project->isEmpty("PRECOMPILED_DIR") && !project->isEmpty("OBJECTS_DIR"))
224         v["PRECOMPILED_DIR"] = v["OBJECTS_DIR"];
225     QString dirs[] = { QString("OBJECTS_DIR"), QString("DESTDIR"), QString("QMAKE_PKGCONFIG_DESTDIR"),
226                        QString("SUBLIBS_DIR"), QString("DLLDESTDIR"), QString("QMAKE_LIBTOOL_DESTDIR"),
227                        QString("PRECOMPILED_DIR"), QString() };
228     for(int x = 0; !dirs[x].isEmpty(); x++) {
229         if(v[dirs[x]].isEmpty())
230             continue;
231         const QString orig_path = v[dirs[x]].first();
232
233         QString &pathRef = v[dirs[x]].first();
234         pathRef = fileFixify(pathRef, Option::output_dir, Option::output_dir);
235
236 #ifdef Q_OS_WIN
237         // We don't want to add a separator for DLLDESTDIR on Windows (###why?)
238         if(!(dirs[x] == "DLLDESTDIR"))
239 #endif
240         {
241             if(!pathRef.endsWith(Option::dir_sep))
242                 pathRef += Option::dir_sep;
243         }
244
245         if(noIO())
246             continue;
247
248         QString path = project->first(dirs[x]); //not to be changed any further
249         path = fileFixify(path, currentDir, Option::output_dir);
250         debug_msg(3, "Fixed output_dir %s (%s) into %s", dirs[x].toLatin1().constData(),
251                   orig_path.toLatin1().constData(), path.toLatin1().constData());
252         if(!mkdir(path))
253             warn_msg(WarnLogic, "%s: Cannot access directory '%s'", dirs[x].toLatin1().constData(),
254                      path.toLatin1().constData());
255     }
256
257     //out paths from the extra compilers
258     const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
259     for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
260         QString tmp_out = project->values((*it) + ".output").first();
261         if(tmp_out.isEmpty())
262             continue;
263         const QStringList &tmp = project->values((*it) + ".input");
264         for(QStringList::ConstIterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) {
265             QStringList &inputs = project->values((*it2));
266             for(QStringList::Iterator input = inputs.begin(); input != inputs.end(); ++input) {
267                 (*input) = fileFixify((*input), Option::output_dir, Option::output_dir);
268                 QString path = unescapeFilePath(replaceExtraCompilerVariables(tmp_out, (*input), QString()));
269                 path = Option::fixPathToTargetOS(path);
270                 int slash = path.lastIndexOf(Option::dir_sep);
271                 if(slash != -1) {
272                     path = path.left(slash);
273                     // Make out path only if it does not contain makefile variables
274                     if(!path.contains("${"))
275                         if(path != "." &&
276                            !mkdir(fileFixify(path, qmake_getpwd(), Option::output_dir)))
277                             warn_msg(WarnLogic, "%s: Cannot access directory '%s'",
278                                      (*it).toLatin1().constData(), path.toLatin1().constData());
279                 }
280             }
281         }
282     }
283
284     if(!v["DESTDIR"].isEmpty()) {
285         QDir d(v["DESTDIR"].first());
286         if(Option::fixPathToLocalOS(d.absolutePath()) == Option::fixPathToLocalOS(Option::output_dir))
287             v.remove("DESTDIR");
288     }
289 }
290
291 QMakeProject
292 *MakefileGenerator::projectFile() const
293 {
294     return project;
295 }
296
297 void
298 MakefileGenerator::setProjectFile(QMakeProject *p)
299 {
300     if(project)
301         return;
302     project = p;
303     if (project->isActiveConfig("win32"))
304         target_mode = TARG_WIN_MODE;
305     else if (project->isActiveConfig("macx"))
306         target_mode = TARG_MACX_MODE;
307     else
308         target_mode = TARG_UNIX_MODE;
309     init();
310     findLibraries();
311     if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE &&
312        project->isActiveConfig("link_prl")) //load up prl's'
313         processPrlFiles();
314 }
315
316 QStringList
317 MakefileGenerator::findFilesInVPATH(QStringList l, uchar flags, const QString &vpath_var)
318 {
319     QStringList vpath;
320     const QHash<QString, QStringList> &v = project->variables();
321     for(int val_it = 0; val_it < l.count(); ) {
322         bool remove_file = false;
323         QString &val = l[val_it];
324         if(!val.isEmpty()) {
325             QString file = fixEnvVariables(val);
326             if(!(flags & VPATH_NoFixify))
327                 file = fileFixify(file, qmake_getpwd(), Option::output_dir);
328             if (file.at(0) == '\"' && file.at(file.length() - 1) == '\"')
329                 file = file.mid(1, file.length() - 2);
330
331             if(exists(file)) {
332                 ++val_it;
333                 continue;
334             }
335             bool found = false;
336             if(QDir::isRelativePath(val)) {
337                 if(vpath.isEmpty()) {
338                     if(!vpath_var.isEmpty())
339                         vpath = v[vpath_var];
340                     vpath += v["VPATH"] + v["QMAKE_ABSOLUTE_SOURCE_PATH"] + v["DEPENDPATH"];
341                     if(Option::output_dir != qmake_getpwd())
342                         vpath += Option::output_dir;
343                 }
344                 for(QStringList::Iterator vpath_it = vpath.begin();
345                     vpath_it != vpath.end(); ++vpath_it) {
346                     QString real_dir = Option::fixPathToLocalOS((*vpath_it));
347                     if(exists(real_dir + QDir::separator() + val)) {
348                         QString dir = (*vpath_it);
349                         if(!dir.endsWith(Option::dir_sep))
350                             dir += Option::dir_sep;
351                         val = dir + val;
352                         if(!(flags & VPATH_NoFixify))
353                             val = fileFixify(val);
354                         found = true;
355                         debug_msg(1, "Found file through vpath %s -> %s",
356                                   file.toLatin1().constData(), val.toLatin1().constData());
357                         break;
358                     }
359                 }
360             }
361             if(!found) {
362                 QString dir, regex = val, real_dir;
363                 if(regex.lastIndexOf(Option::dir_sep) != -1) {
364                     dir = regex.left(regex.lastIndexOf(Option::dir_sep) + 1);
365                     real_dir = dir;
366                     if(!(flags & VPATH_NoFixify))
367                         real_dir = fileFixify(real_dir, qmake_getpwd(), Option::output_dir) + '/';
368                     regex.remove(0, dir.length());
369                 }
370                 if(real_dir.isEmpty() || exists(real_dir)) {
371                     QStringList files = QDir(real_dir).entryList(QStringList(regex));
372                     if(files.isEmpty()) {
373                         debug_msg(1, "%s:%d Failure to find %s in vpath (%s)",
374                                   __FILE__, __LINE__,
375                                   val.toLatin1().constData(), vpath.join("::").toLatin1().constData());
376                         if(flags & VPATH_RemoveMissingFiles)
377                             remove_file = true;
378                         else if(flags & VPATH_WarnMissingFiles)
379                             warn_msg(WarnLogic, "Failure to find: %s", val.toLatin1().constData());
380                     } else {
381                         l.removeAt(val_it);
382                         QString a;
383                         for(int i = (int)files.count()-1; i >= 0; i--) {
384                             if(files[i] == "." || files[i] == "..")
385                                 continue;
386                             a = real_dir + files[i];
387                             if(!(flags & VPATH_NoFixify))
388                                 a = fileFixify(a);
389                             l.insert(val_it, a);
390                         }
391                     }
392                 } else {
393                     debug_msg(1, "%s:%d Cannot match %s%s, as %s does not exist.",
394                               __FILE__, __LINE__, real_dir.toLatin1().constData(),
395                               regex.toLatin1().constData(), real_dir.toLatin1().constData());
396                     if(flags & VPATH_RemoveMissingFiles)
397                         remove_file = true;
398                     else if(flags & VPATH_WarnMissingFiles)
399                         warn_msg(WarnLogic, "Failure to find: %s", val.toLatin1().constData());
400                 }
401             }
402         }
403         if(remove_file)
404             l.removeAt(val_it);
405         else
406             ++val_it;
407     }
408     return l;
409 }
410
411 void
412 MakefileGenerator::initCompiler(const MakefileGenerator::Compiler &comp)
413 {
414     QHash<QString, QStringList> &v = project->variables();
415     QStringList &l = v[comp.variable_in];
416     // find all the relevant file inputs
417     if(!init_compiler_already.contains(comp.variable_in)) {
418         init_compiler_already.insert(comp.variable_in, true);
419         if(!noIO())
420             l = findFilesInVPATH(l, (comp.flags & Compiler::CompilerRemoveNoExist) ?
421                                  VPATH_RemoveMissingFiles : VPATH_WarnMissingFiles, "VPATH_" + comp.variable_in);
422     }
423 }
424
425 void
426 MakefileGenerator::init()
427 {
428     initOutPaths();
429     if(init_already)
430         return;
431     verifyCompilers();
432     init_already = true;
433
434     QHash<QString, QStringList> &v = project->variables();
435
436     chkdir = v["QMAKE_CHK_DIR_EXISTS"].join(" ");
437     chkfile = v["QMAKE_CHK_FILE_EXISTS"].join(" ");
438     if (chkfile.isEmpty()) // Backwards compat with Qt4 specs
439         chkfile = isWindowsShell() ? "if not exist" : "test -f";
440     chkglue = v["QMAKE_CHK_EXISTS_GLUE"].join(" ");
441     if (chkglue.isEmpty()) // Backwards compat with Qt4 specs
442         chkglue = isWindowsShell() ? "" : "|| ";
443
444     QStringList &quc = v["QMAKE_EXTRA_COMPILERS"];
445
446     //make sure the COMPILERS are in the correct input/output chain order
447     for(int comp_out = 0, jump_count = 0; comp_out < quc.size(); ++comp_out) {
448     continue_compiler_chain:
449         if(jump_count > quc.size()) //just to avoid an infinite loop here
450             break;
451         if (v.contains(quc.at(comp_out) + ".variable_out")) {
452             const QStringList &outputs = v.value(quc.at(comp_out) + ".variable_out");
453             for(int out = 0; out < outputs.size(); ++out) {
454                 for(int comp_in = 0; comp_in < quc.size(); ++comp_in) {
455                     if(comp_in == comp_out)
456                         continue;
457                     if (v.contains(quc.at(comp_in) + ".input")) {
458                         const QStringList &inputs = v.value(quc.at(comp_in) + ".input");
459                         for(int in = 0; in < inputs.size(); ++in) {
460                             if(inputs.at(in) == outputs.at(out) && comp_out > comp_in) {
461                                 ++jump_count;
462                                 //move comp_out to comp_in and continue the compiler chain
463                                 quc.move(comp_out, comp_in);
464                                 comp_out = comp_in;
465                                 goto continue_compiler_chain;
466                             }
467                         }
468                     }
469                 }
470             }
471         }
472     }
473
474     if(!project->isEmpty("QMAKE_SUBSTITUTES")) {
475         const QStringList &subs = v["QMAKE_SUBSTITUTES"];
476         for(int i = 0; i < subs.size(); ++i) {
477             QString inn = subs.at(i) + ".input", outn = subs.at(i) + ".output";
478             if (v.contains(inn) || v.contains(outn)) {
479                 if (!v.contains(inn) || !v.contains(outn)) {
480                     warn_msg(WarnLogic, "Substitute '%s' has only one of .input and .output",
481                              subs.at(i).toLatin1().constData());
482                     continue;
483                 }
484                 const QStringList &tinn = v[inn], &toutn = v[outn];
485                 if (tinn.length() != 1) {
486                     warn_msg(WarnLogic, "Substitute '%s.input' does not have exactly one value",
487                              subs.at(i).toLatin1().constData());
488                     continue;
489                 }
490                 if (toutn.length() != 1) {
491                     warn_msg(WarnLogic, "Substitute '%s.output' does not have exactly one value",
492                              subs.at(i).toLatin1().constData());
493                     continue;
494                 }
495                 inn = fileFixify(tinn.first(), qmake_getpwd());
496                 outn = fileFixify(toutn.first(), qmake_getpwd(), Option::output_dir);
497             } else {
498                 inn = fileFixify(subs.at(i), qmake_getpwd());
499                 if (!QFile::exists(inn)) {
500                     // random insanity for backwards compat: .in file specified with absolute out dir
501                     inn = fileFixify(subs.at(i));
502                 }
503                 if(!inn.endsWith(".in")) {
504                     warn_msg(WarnLogic, "Substitute '%s' does not end with '.in'",
505                              inn.toLatin1().constData());
506                     continue;
507                 }
508                 outn = fileFixify(inn.left(inn.length()-3), qmake_getpwd(), Option::output_dir);
509             }
510
511             QString confign = subs.at(i) + ".CONFIG";
512             bool verbatim  = false;
513             if (v.contains(confign))
514                 verbatim = v[confign].contains(QLatin1String("verbatim"));
515
516             QFile in(inn);
517             if (in.open(QFile::ReadOnly)) {
518                 QByteArray contentBytes;
519                 if (verbatim) {
520                     contentBytes = in.readAll();
521                 } else {
522                     QString contents;
523                     QStack<int> state;
524                     enum { IN_CONDITION, MET_CONDITION, PENDING_CONDITION };
525                     for (int count = 1; !in.atEnd(); ++count) {
526                         QString line = QString::fromUtf8(in.readLine());
527                         if (line.startsWith("!!IF ")) {
528                             if (state.isEmpty() || state.top() == IN_CONDITION) {
529                                 QString test = line.mid(5, line.length()-(5+1));
530                                 if (project->test(test))
531                                     state.push(IN_CONDITION);
532                                 else
533                                     state.push(PENDING_CONDITION);
534                             } else {
535                                 state.push(MET_CONDITION);
536                             }
537                         } else if (line.startsWith("!!ELIF ")) {
538                             if (state.isEmpty()) {
539                                 warn_msg(WarnLogic, "(%s:%d): Unexpected else condition",
540                                         in.fileName().toLatin1().constData(), count);
541                             } else if (state.top() == PENDING_CONDITION) {
542                                 QString test = line.mid(7, line.length()-(7+1));
543                                 if (project->test(test))  {
544                                     state.pop();
545                                     state.push(IN_CONDITION);
546                                 }
547                             } else if (state.top() == IN_CONDITION) {
548                                 state.pop();
549                                 state.push(MET_CONDITION);
550                             }
551                         } else if (line.startsWith("!!ELSE")) {
552                             if (state.isEmpty()) {
553                                 warn_msg(WarnLogic, "(%s:%d): Unexpected else condition",
554                                         in.fileName().toLatin1().constData(), count);
555                             } else if (state.top() == PENDING_CONDITION) {
556                                 state.pop();
557                                 state.push(IN_CONDITION);
558                             } else if (state.top() == IN_CONDITION) {
559                                 state.pop();
560                                 state.push(MET_CONDITION);
561                             }
562                         } else if (line.startsWith("!!ENDIF")) {
563                             if (state.isEmpty())
564                                 warn_msg(WarnLogic, "(%s:%d): Unexpected endif",
565                                         in.fileName().toLatin1().constData(), count);
566                             else
567                                 state.pop();
568                         } else if (state.isEmpty() || state.top() == IN_CONDITION) {
569                             contents += project->expand(line, in.fileName(), count);
570                         }
571                     }
572                     contentBytes = contents.toUtf8();
573                 }
574                 QFile out(outn);
575                 if (out.exists() && out.open(QFile::ReadOnly)) {
576                     QByteArray old = out.readAll();
577                     if (contentBytes == old) {
578                         v["QMAKE_INTERNAL_INCLUDED_FILES"].append(in.fileName());
579                         continue;
580                     }
581                     out.close();
582                     if(!out.remove()) {
583                         warn_msg(WarnLogic, "Cannot clear substitute '%s'",
584                                  out.fileName().toLatin1().constData());
585                         continue;
586                     }
587                 }
588                 mkdir(QFileInfo(out).absolutePath());
589                 if(out.open(QFile::WriteOnly)) {
590                     v["QMAKE_INTERNAL_INCLUDED_FILES"].append(in.fileName());
591                     out.write(contentBytes);
592                 } else {
593                     warn_msg(WarnLogic, "Cannot open substitute for output '%s'",
594                              out.fileName().toLatin1().constData());
595                 }
596             } else {
597                 warn_msg(WarnLogic, "Cannot open substitute for input '%s'",
598                          in.fileName().toLatin1().constData());
599             }
600         }
601     }
602
603     int x;
604
605     //build up a list of compilers
606     QList<Compiler> compilers;
607     {
608         const char *builtins[] = { "OBJECTS", "SOURCES", "PRECOMPILED_HEADER", 0 };
609         for(x = 0; builtins[x]; ++x) {
610             Compiler compiler;
611             compiler.variable_in = builtins[x];
612             compiler.flags = Compiler::CompilerBuiltin;
613             compiler.type = QMakeSourceFileInfo::TYPE_C;
614             if(!strcmp(builtins[x], "OBJECTS"))
615                 compiler.flags |= Compiler::CompilerNoCheckDeps;
616             compilers.append(compiler);
617         }
618         for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
619             const QStringList &inputs = v[(*it) + ".input"];
620             for(x = 0; x < inputs.size(); ++x) {
621                 Compiler compiler;
622                 compiler.variable_in = inputs.at(x);
623                 compiler.flags = Compiler::CompilerNoFlags;
624                 if(v[(*it) + ".CONFIG"].indexOf("ignore_no_exist") != -1)
625                     compiler.flags |= Compiler::CompilerRemoveNoExist;
626                 if(v[(*it) + ".CONFIG"].indexOf("no_dependencies") != -1)
627                     compiler.flags |= Compiler::CompilerNoCheckDeps;
628                 if(v[(*it) + ".CONFIG"].indexOf("add_inputs_as_makefile_deps") != -1)
629                     compiler.flags |= Compiler::CompilerAddInputsAsMakefileDeps;
630
631                 QString dep_type;
632                 if(!project->isEmpty((*it) + ".dependency_type"))
633                     dep_type = project->first((*it) + ".dependency_type");
634                 if (dep_type.isEmpty())
635                     compiler.type = QMakeSourceFileInfo::TYPE_UNKNOWN;
636                 else if(dep_type == "TYPE_UI")
637                     compiler.type = QMakeSourceFileInfo::TYPE_UI;
638                 else
639                     compiler.type = QMakeSourceFileInfo::TYPE_C;
640                 compilers.append(compiler);
641             }
642         }
643     }
644     { //do the path fixifying
645         QStringList paths;
646         for(x = 0; x < compilers.count(); ++x) {
647             if(!paths.contains(compilers.at(x).variable_in))
648                 paths << compilers.at(x).variable_in;
649         }
650         paths << "INCLUDEPATH" << "QMAKE_INTERNAL_INCLUDED_FILES" << "PRECOMPILED_HEADER";
651         for(int y = 0; y < paths.count(); y++) {
652             QStringList &l = v[paths[y]];
653             for(QStringList::Iterator it = l.begin(); it != l.end(); ++it) {
654                 if((*it).isEmpty())
655                     continue;
656                 if(exists((*it)))
657                     (*it) = fileFixify((*it));
658             }
659         }
660     }
661
662     if(noIO() || !doDepends() || project->isActiveConfig("GNUmake"))
663         QMakeSourceFileInfo::setDependencyMode(QMakeSourceFileInfo::NonRecursive);
664     for(x = 0; x < compilers.count(); ++x)
665         initCompiler(compilers.at(x));
666
667     //merge actual compiler outputs into their variable_out. This is done last so that
668     //files are already properly fixified.
669     for(QStringList::Iterator it = quc.begin(); it != quc.end(); ++it) {
670         QString tmp_out = project->values((*it) + ".output").first();
671         if(tmp_out.isEmpty())
672             continue;
673         if(project->values((*it) + ".CONFIG").indexOf("combine") != -1) {
674             const QStringList &compilerInputs = project->values((*it) + ".input");
675             // Don't generate compiler output if it doesn't have input.
676             if (compilerInputs.isEmpty() || project->values(compilerInputs.first()).isEmpty())
677                 continue;
678             if(tmp_out.indexOf("$") == -1) {
679                 if(!verifyExtraCompiler((*it), QString())) //verify
680                     continue;
681                 QString out = fileFixify(tmp_out, Option::output_dir, Option::output_dir);
682                 bool pre_dep = (project->values((*it) + ".CONFIG").indexOf("target_predeps") != -1);
683                 if (v.contains((*it) + ".variable_out")) {
684                     const QStringList &var_out = v.value((*it) + ".variable_out");
685                     for(int i = 0; i < var_out.size(); ++i) {
686                         QString v = var_out.at(i);
687                         if(v == QLatin1String("SOURCES"))
688                             v = "GENERATED_SOURCES";
689                         else if(v == QLatin1String("OBJECTS"))
690                             pre_dep = false;
691                         QStringList &list = project->values(v);
692                         if(!list.contains(out))
693                             list.append(out);
694                     }
695                 } else if(project->values((*it) + ".CONFIG").indexOf("no_link") == -1) {
696                     QStringList &list = project->values("OBJECTS");
697                     pre_dep = false;
698                     if(!list.contains(out))
699                         list.append(out);
700                 } else {
701                         QStringList &list = project->values("UNUSED_SOURCES");
702                         if(!list.contains(out))
703                             list.append(out);
704                 }
705                 if(pre_dep) {
706                     QStringList &list = project->values("PRE_TARGETDEPS");
707                     if(!list.contains(out))
708                         list.append(out);
709                 }
710             }
711         } else {
712             const QStringList &tmp = project->values((*it) + ".input");
713             for (QStringList::ConstIterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) {
714                 const QStringList inputs = project->values((*it2));
715                 for(QStringList::ConstIterator input = inputs.constBegin(); input != inputs.constEnd(); ++input) {
716                     if((*input).isEmpty())
717                         continue;
718                     QString in = Option::fixPathToTargetOS((*input), false);
719                     if(!verifyExtraCompiler((*it), in)) //verify
720                         continue;
721                     QString out = replaceExtraCompilerVariables(tmp_out, (*input), QString());
722                     out = fileFixify(out, Option::output_dir, Option::output_dir);
723                     bool pre_dep = (project->values((*it) + ".CONFIG").indexOf("target_predeps") != -1);
724                     if (v.contains((*it) + ".variable_out")) {
725                         const QStringList &var_out = project->values(*it + ".variable_out");
726                         for(int i = 0; i < var_out.size(); ++i) {
727                             QString v = var_out.at(i);
728                             if(v == QLatin1String("SOURCES"))
729                                 v = "GENERATED_SOURCES";
730                             else if(v == QLatin1String("OBJECTS"))
731                                 pre_dep = false;
732                             QStringList &list = project->values(v);
733                             if(!list.contains(out))
734                                 list.append(out);
735                         }
736                     } else if(project->values((*it) + ".CONFIG").indexOf("no_link") == -1) {
737                         pre_dep = false;
738                         QStringList &list = project->values("OBJECTS");
739                         if(!list.contains(out))
740                             list.append(out);
741                     } else {
742                         QStringList &list = project->values("UNUSED_SOURCES");
743                         if(!list.contains(out))
744                             list.append(out);
745                     }
746                     if(pre_dep) {
747                         QStringList &list = project->values("PRE_TARGETDEPS");
748                         if(!list.contains(out))
749                             list.append(out);
750                     }
751                 }
752             }
753         }
754     }
755
756     //handle dependencies
757     depHeuristicsCache.clear();
758     if(!noIO()) {
759         // dependency paths
760         QStringList incDirs = v["DEPENDPATH"] + v["QMAKE_ABSOLUTE_SOURCE_PATH"];
761         if(project->isActiveConfig("depend_includepath"))
762             incDirs += v["INCLUDEPATH"];
763         if(!project->isActiveConfig("no_include_pwd")) {
764             QString pwd = qmake_getpwd();
765             if(pwd.isEmpty())
766                 pwd = ".";
767             incDirs += pwd;
768         }
769         QList<QMakeLocalFileName> deplist;
770         for(QStringList::Iterator it = incDirs.begin(); it != incDirs.end(); ++it)
771             deplist.append(QMakeLocalFileName(unescapeFilePath((*it))));
772         QMakeSourceFileInfo::setDependencyPaths(deplist);
773         debug_msg(1, "Dependency Directories: %s", incDirs.join(" :: ").toLatin1().constData());
774         //cache info
775         if(project->isActiveConfig("qmake_cache")) {
776             QString cache_file;
777             if(!project->isEmpty("QMAKE_INTERNAL_CACHE_FILE")) {
778                 cache_file = QDir::fromNativeSeparators(project->first("QMAKE_INTERNAL_CACHE_FILE"));
779             } else {
780                 cache_file = ".qmake.internal.cache";
781                 if(project->isActiveConfig("build_pass"))
782                     cache_file += ".BUILD." + project->first("BUILD_PASS");
783             }
784             if(cache_file.indexOf('/') == -1)
785                 cache_file.prepend(Option::output_dir + '/');
786             QMakeSourceFileInfo::setCacheFile(cache_file);
787         }
788
789         //add to dependency engine
790         for(x = 0; x < compilers.count(); ++x) {
791             const MakefileGenerator::Compiler &comp = compilers.at(x);
792             if(!(comp.flags & Compiler::CompilerNoCheckDeps)) {
793                 addSourceFiles(v[comp.variable_in], QMakeSourceFileInfo::SEEK_DEPS,
794                                (QMakeSourceFileInfo::SourceFileType)comp.type);
795
796                 if (comp.flags & Compiler::CompilerAddInputsAsMakefileDeps) {
797                     QStringList &l = v[comp.variable_in];
798                     for (int i=0; i < l.size(); ++i) {
799                         if(v["QMAKE_INTERNAL_INCLUDED_FILES"].indexOf(l.at(i)) == -1)
800                             v["QMAKE_INTERNAL_INCLUDED_FILES"].append(l.at(i));
801                     }
802                 }
803             }
804         }
805     }
806
807     processSources(); //remove anything in SOURCES which is included (thus it need not be linked in)
808
809     //all sources and generated sources must be turned into objects at some point (the one builtin compiler)
810     v["OBJECTS"] += createObjectList(v["SOURCES"]) + createObjectList(v["GENERATED_SOURCES"]);
811
812     //Translation files
813     if(!project->isEmpty("TRANSLATIONS")) {
814         QStringList &trf = project->values("TRANSLATIONS");
815         for(QStringList::Iterator it = trf.begin(); it != trf.end(); ++it)
816             (*it) = Option::fixPathToLocalOS((*it));
817     }
818
819     if(!project->isActiveConfig("no_include_pwd")) { //get the output_dir into the pwd
820         if(Option::output_dir != qmake_getpwd())
821             project->values("INCLUDEPATH").append(".");
822     }
823
824     //fix up the target deps
825     QString fixpaths[] = { QString("PRE_TARGETDEPS"), QString("POST_TARGETDEPS"), QString() };
826     for(int path = 0; !fixpaths[path].isNull(); path++) {
827         QStringList &l = v[fixpaths[path]];
828         for(QStringList::Iterator val_it = l.begin(); val_it != l.end(); ++val_it) {
829             if(!(*val_it).isEmpty())
830                 (*val_it) = escapeDependencyPath(Option::fixPathToTargetOS((*val_it), false, false));
831         }
832     }
833
834     //extra depends
835     if(!project->isEmpty("DEPENDS")) {
836         QStringList &l = v["DEPENDS"];
837         for(QStringList::Iterator it = l.begin(); it != l.end(); ++it) {
838             QStringList files = v[(*it) + ".file"] + v[(*it) + ".files"]; //why do I support such evil things?
839             for(QStringList::Iterator file_it = files.begin(); file_it != files.end(); ++file_it) {
840                 QStringList &out_deps = findDependencies(*file_it);
841                 QStringList &in_deps = v[(*it) + ".depends"]; //even more evilness..
842                 for(QStringList::Iterator dep_it = in_deps.begin(); dep_it != in_deps.end(); ++dep_it) {
843                     if(exists(*dep_it)) {
844                         out_deps.append(*dep_it);
845                     } else {
846                         QString dir, regex = Option::fixPathToLocalOS((*dep_it));
847                         if(regex.lastIndexOf(Option::dir_sep) != -1) {
848                             dir = regex.left(regex.lastIndexOf(Option::dir_sep) + 1);
849                             regex.remove(0, dir.length());
850                         }
851                         QStringList files = QDir(dir).entryList(QStringList(regex));
852                         if(files.isEmpty()) {
853                             warn_msg(WarnLogic, "Dependency for [%s]: Not found %s", (*file_it).toLatin1().constData(),
854                                      (*dep_it).toLatin1().constData());
855                         } else {
856                             for(int i = 0; i < files.count(); i++)
857                                 out_deps.append(dir + files[i]);
858                         }
859                     }
860                 }
861             }
862         }
863     }
864
865     // escape qmake command
866     project->values("QMAKE_QMAKE") =
867             escapeFilePaths(QStringList(Option::fixPathToTargetOS(Option::qmake_abslocation, false)));
868 }
869
870 bool
871 MakefileGenerator::processPrlFile(QString &file)
872 {
873     bool ret = false, try_replace_file=false;
874     QString meta_file, orig_file = file;
875     if(QMakeMetaInfo::libExists(file)) {
876         try_replace_file = true;
877         meta_file = file;
878         file = "";
879     } else {
880         QString tmp = file;
881         int ext = tmp.lastIndexOf('.');
882         if(ext != -1)
883             tmp = tmp.left(ext);
884         meta_file = tmp;
885     }
886 //    meta_file = fileFixify(meta_file);
887     QString real_meta_file = Option::fixPathToLocalOS(meta_file);
888     if(!meta_file.isEmpty()) {
889         QString f = fileFixify(real_meta_file, qmake_getpwd(), Option::output_dir);
890         if(QMakeMetaInfo::libExists(f)) {
891             QMakeMetaInfo libinfo;
892             debug_msg(1, "Processing PRL file: %s", real_meta_file.toLatin1().constData());
893             if(!libinfo.readLib(f)) {
894                 fprintf(stderr, "Error processing meta file: %s\n", real_meta_file.toLatin1().constData());
895             } else if(project->isActiveConfig("no_read_prl_" + libinfo.type().toLower())) {
896                 debug_msg(2, "Ignored meta file %s [%s]", real_meta_file.toLatin1().constData(), libinfo.type().toLatin1().constData());
897             } else {
898                 ret = true;
899                 project->values("QMAKE_CURRENT_PRL_LIBS") = libinfo.values("QMAKE_PRL_LIBS");
900                 QStringList &defs = project->values("DEFINES");
901                 const QStringList &prl_defs = project->values("PRL_EXPORT_DEFINES");
902                 foreach (const QString &def, libinfo.values("QMAKE_PRL_DEFINES"))
903                     if (!defs.contains(def) && prl_defs.contains(def))
904                         defs.append(def);
905                 if(try_replace_file && !libinfo.isEmpty("QMAKE_PRL_TARGET")) {
906                     QString dir;
907                     int slsh = real_meta_file.lastIndexOf(Option::dir_sep);
908                     if(slsh != -1)
909                         dir = real_meta_file.left(slsh+1);
910                     file = libinfo.first("QMAKE_PRL_TARGET");
911                     if(QDir::isRelativePath(file))
912                         file.prepend(dir);
913                 }
914             }
915         }
916         if(ret) {
917             QString mf = QMakeMetaInfo::findLib(meta_file);
918             if(project->values("QMAKE_PRL_INTERNAL_FILES").indexOf(mf) == -1)
919                project->values("QMAKE_PRL_INTERNAL_FILES").append(mf);
920             if(project->values("QMAKE_INTERNAL_INCLUDED_FILES").indexOf(mf) == -1)
921                project->values("QMAKE_INTERNAL_INCLUDED_FILES").append(mf);
922         }
923     }
924     if(try_replace_file && file.isEmpty()) {
925 #if 0
926         warn_msg(WarnLogic, "Found prl [%s] file with no target [%s]!", meta_file.toLatin1().constData(),
927                  orig_file.toLatin1().constData());
928 #endif
929         file = orig_file;
930     }
931     return ret;
932 }
933
934 void
935 MakefileGenerator::filterIncludedFiles(const QString &var)
936 {
937     QStringList &inputs = project->values(var);
938     for(QStringList::Iterator input = inputs.begin(); input != inputs.end(); ) {
939         if(QMakeSourceFileInfo::included((*input)) > 0)
940             input = inputs.erase(input);
941         else
942             ++input;
943     }
944 }
945
946 void
947 MakefileGenerator::processPrlFiles()
948 {
949     qFatal("MakefileGenerator::processPrlFiles() called!");
950 }
951
952 void
953 MakefileGenerator::writePrlFile(QTextStream &t)
954 {
955     QString target = project->first("TARGET");
956     int slsh = target.lastIndexOf(Option::dir_sep);
957     if(slsh != -1)
958         target.remove(0, slsh + 1);
959     QString bdir = Option::output_dir;
960     if(bdir.isEmpty())
961         bdir = qmake_getpwd();
962     t << "QMAKE_PRL_BUILD_DIR = " << bdir << endl;
963
964     if(!project->projectFile().isEmpty() && project->projectFile() != "-")
965         t << "QMAKE_PRO_INPUT = " << project->projectFile().section('/', -1) << endl;
966
967     if(!project->isEmpty("QMAKE_ABSOLUTE_SOURCE_PATH"))
968         t << "QMAKE_PRL_SOURCE_DIR = " << project->first("QMAKE_ABSOLUTE_SOURCE_PATH") << endl;
969     t << "QMAKE_PRL_TARGET = " << target << endl;
970     if(!project->isEmpty("PRL_EXPORT_DEFINES"))
971         t << "QMAKE_PRL_DEFINES = " << project->values("PRL_EXPORT_DEFINES").join(" ") << endl;
972     if(!project->isEmpty("PRL_EXPORT_CFLAGS"))
973         t << "QMAKE_PRL_CFLAGS = " << project->values("PRL_EXPORT_CFLAGS").join(" ") << endl;
974     if(!project->isEmpty("PRL_EXPORT_CXXFLAGS"))
975         t << "QMAKE_PRL_CXXFLAGS = " << project->values("PRL_EXPORT_CXXFLAGS").join(" ") << endl;
976     if(!project->isEmpty("CONFIG"))
977         t << "QMAKE_PRL_CONFIG = " << project->values("CONFIG").join(" ") << endl;
978     if(!project->isEmpty("TARGET_VERSION_EXT"))
979         t << "QMAKE_PRL_VERSION = " << project->first("TARGET_VERSION_EXT") << endl;
980     else if(!project->isEmpty("VERSION"))
981         t << "QMAKE_PRL_VERSION = " << project->first("VERSION") << endl;
982     if(project->isActiveConfig("staticlib") || project->isActiveConfig("explicitlib")) {
983         QStringList libs;
984         if(!project->isEmpty("QMAKE_INTERNAL_PRL_LIBS"))
985             libs = project->values("QMAKE_INTERNAL_PRL_LIBS");
986         else
987             libs << "QMAKE_LIBS"; //obvious one
988         if(project->isActiveConfig("staticlib"))
989             libs << "QMAKE_LIBS_PRIVATE";
990         t << "QMAKE_PRL_LIBS = ";
991         for(QStringList::Iterator it = libs.begin(); it != libs.end(); ++it)
992             t << project->values((*it)).join(" ").replace('\\', "\\\\") << " ";
993         t << endl;
994     }
995 }
996
997 bool
998 MakefileGenerator::writeProjectMakefile()
999 {
1000     QTextStream t(&Option::output);
1001
1002     //header
1003     writeHeader(t);
1004
1005     QList<SubTarget*> targets;
1006     {
1007         QStringList builds = project->values("BUILDS");
1008         for(QStringList::Iterator it = builds.begin(); it != builds.end(); ++it) {
1009             SubTarget *st = new SubTarget;
1010             targets.append(st);
1011             st->makefile = "$(MAKEFILE)." + (*it);
1012             st->name = (*it);
1013             st->target = project->isEmpty((*it) + ".target") ? (*it) : project->first((*it) + ".target");
1014         }
1015     }
1016     if(project->isActiveConfig("build_all")) {
1017         t << "first: all" << endl;
1018         QList<SubTarget*>::Iterator it;
1019
1020         //install
1021         t << "install: ";
1022         for(it = targets.begin(); it != targets.end(); ++it)
1023             t << (*it)->target << "-install ";
1024         t << endl;
1025
1026         //uninstall
1027         t << "uninstall: ";
1028         for(it = targets.begin(); it != targets.end(); ++it)
1029             t << (*it)->target << "-uninstall ";
1030         t << endl;
1031     } else {
1032         t << "first: " << targets.first()->target << endl
1033           << "install: " << targets.first()->target << "-install" << endl
1034           << "uninstall: " << targets.first()->target << "-uninstall" << endl;
1035     }
1036
1037     writeSubTargets(t, targets, SubTargetsNoFlags);
1038     if(!project->isActiveConfig("no_autoqmake")) {
1039         for(QList<SubTarget*>::Iterator it = targets.begin(); it != targets.end(); ++it)
1040             t << (*it)->makefile << ": " <<
1041                 Option::fixPathToTargetOS(fileFixify(Option::output.fileName())) << endl;
1042     }
1043     qDeleteAll(targets);
1044     return true;
1045 }
1046
1047 bool
1048 MakefileGenerator::write()
1049 {
1050     if(!project)
1051         return false;
1052     writePrlFile();
1053     if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE || //write makefile
1054        Option::qmake_mode == Option::QMAKE_GENERATE_PROJECT) {
1055         QTextStream t(&Option::output);
1056         if(!writeMakefile(t)) {
1057 #if 1
1058             warn_msg(WarnLogic, "Unable to generate output for: %s [TEMPLATE %s]",
1059                      Option::output.fileName().toLatin1().constData(),
1060                      project->first("TEMPLATE").toLatin1().constData());
1061             if(Option::output.exists())
1062                 Option::output.remove();
1063 #endif
1064         }
1065     }
1066     return true;
1067 }
1068
1069 QString
1070 MakefileGenerator::prlFileName(bool fixify)
1071 {
1072     QString ret = project->first("TARGET_PRL");;
1073     if(ret.isEmpty())
1074         ret = project->first("TARGET");
1075     int slsh = ret.lastIndexOf(Option::dir_sep);
1076     if(slsh != -1)
1077         ret.remove(0, slsh);
1078     if(!ret.endsWith(Option::prl_ext)) {
1079         int dot = ret.indexOf('.');
1080         if(dot != -1)
1081             ret.truncate(dot);
1082         ret += Option::prl_ext;
1083     }
1084     if(!project->isEmpty("QMAKE_BUNDLE"))
1085         ret.prepend(project->first("QMAKE_BUNDLE") + Option::dir_sep);
1086     if(fixify) {
1087         if(!project->isEmpty("DESTDIR"))
1088             ret.prepend(project->first("DESTDIR"));
1089         ret = Option::fixPathToLocalOS(fileFixify(ret, qmake_getpwd(), Option::output_dir));
1090     }
1091     return ret;
1092 }
1093
1094 void
1095 MakefileGenerator::writePrlFile()
1096 {
1097     if((Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE ||
1098             Option::qmake_mode == Option::QMAKE_GENERATE_PRL)
1099        && project->values("QMAKE_FAILED_REQUIREMENTS").isEmpty()
1100        && project->isActiveConfig("create_prl")
1101        && (project->first("TEMPLATE") == "lib"
1102        || project->first("TEMPLATE") == "vclib")
1103        && (!project->isActiveConfig("plugin") || project->isActiveConfig("static"))) { //write prl file
1104         QString local_prl = prlFileName();
1105         QString prl = fileFixify(local_prl);
1106         mkdir(fileInfo(local_prl).path());
1107         QFile ft(local_prl);
1108         if(ft.open(QIODevice::WriteOnly)) {
1109             project->values("ALL_DEPS").append(prl);
1110             project->values("QMAKE_INTERNAL_PRL_FILE").append(prl);
1111             QTextStream t(&ft);
1112             writePrlFile(t);
1113         }
1114     }
1115 }
1116
1117 void
1118 MakefileGenerator::writeObj(QTextStream &t, const QString &src)
1119 {
1120     const QStringList &srcl = project->values(src);
1121     const QStringList objl = createObjectList(srcl);
1122
1123     QStringList::ConstIterator oit = objl.begin();
1124     QStringList::ConstIterator sit = srcl.begin();
1125     QString stringSrc("$src");
1126     QString stringObj("$obj");
1127     for(;sit != srcl.end() && oit != objl.end(); ++oit, ++sit) {
1128         if((*sit).isEmpty())
1129             continue;
1130
1131         t << escapeDependencyPath((*oit)) << ": " << escapeDependencyPath((*sit)) << " " << escapeDependencyPaths(findDependencies((*sit))).join(" \\\n\t\t");
1132
1133         QString comp, cimp;
1134         for(QStringList::Iterator cppit = Option::cpp_ext.begin(); cppit != Option::cpp_ext.end(); ++cppit) {
1135             if((*sit).endsWith((*cppit))) {
1136                 comp = "QMAKE_RUN_CXX";
1137                 cimp = "QMAKE_RUN_CXX_IMP";
1138                 break;
1139             }
1140         }
1141         if(comp.isEmpty()) {
1142             comp = "QMAKE_RUN_CC";
1143             cimp = "QMAKE_RUN_CC_IMP";
1144         }
1145         bool use_implicit_rule = !project->isEmpty(cimp);
1146         use_implicit_rule = false;
1147         if(use_implicit_rule) {
1148             if(!project->isEmpty("OBJECTS_DIR")) {
1149                 use_implicit_rule = false;
1150             } else {
1151                 int dot = (*sit).lastIndexOf('.');
1152                 if(dot == -1 || ((*sit).left(dot) + Option::obj_ext != (*oit)))
1153                     use_implicit_rule = false;
1154             }
1155         }
1156         if (!use_implicit_rule && !project->isEmpty(comp)) {
1157             QString p = var(comp), srcf(*sit);
1158             p.replace(stringSrc, escapeFilePath(srcf));
1159             p.replace(stringObj, escapeFilePath((*oit)));
1160             t << "\n\t" << p;
1161         }
1162         t << endl << endl;
1163     }
1164 }
1165
1166 QString
1167 MakefileGenerator::filePrefixRoot(const QString &root, const QString &path)
1168 {
1169     QString ret(root + path);
1170     if(path.length() > 2 && path[1] == ':') //c:\foo
1171         ret = QString(path.mid(0, 2) + root + path.mid(2));
1172     while(ret.endsWith("\\"))
1173         ret = ret.left(ret.length()-1);
1174     return ret;
1175 }
1176
1177 void
1178 MakefileGenerator::writeInstalls(QTextStream &t, const QString &installs, bool noBuild)
1179 {
1180     QString rm_dir_contents("-$(DEL_FILE)");
1181     if (!isWindowsShell()) //ick
1182         rm_dir_contents = "-$(DEL_FILE) -r";
1183
1184     QString all_installs, all_uninstalls;
1185     const QStringList &l = project->values(installs);
1186     for (QStringList::ConstIterator it = l.begin(); it != l.end(); ++it) {
1187         QString pvar = (*it) + ".path";
1188         if(project->values((*it) + ".CONFIG").indexOf("no_path") == -1 &&
1189            project->values((*it) + ".CONFIG").indexOf("dummy_install") == -1 &&
1190            project->values(pvar).isEmpty()) {
1191             warn_msg(WarnLogic, "%s is not defined: install target not created\n", pvar.toLatin1().constData());
1192             continue;
1193         }
1194
1195         bool do_default = true;
1196         const QString root = "$(INSTALL_ROOT)";
1197         QString target, dst;
1198         if(project->values((*it) + ".CONFIG").indexOf("no_path") == -1 &&
1199            project->values((*it) + ".CONFIG").indexOf("dummy_install") == -1) {
1200             dst = fileFixify(unescapeFilePath(project->values(pvar).first()), FileFixifyAbsolute, false);
1201             if(!dst.endsWith(Option::dir_sep))
1202                 dst += Option::dir_sep;
1203         }
1204
1205         QStringList tmp, uninst = project->values((*it) + ".uninstall");
1206         //other
1207         tmp = project->values((*it) + ".extra");
1208         if(tmp.isEmpty())
1209             tmp = project->values((*it) + ".commands"); //to allow compatible name
1210         if(!tmp.isEmpty()) {
1211             do_default = false;
1212             if(!target.isEmpty())
1213                 target += "\n\t";
1214             target += tmp.join(" ");
1215         }
1216         //masks
1217         tmp = findFilesInVPATH(project->values((*it) + ".files"), VPATH_NoFixify);
1218         tmp = fileFixify(tmp, FileFixifyAbsolute);
1219         if(!tmp.isEmpty()) {
1220             if(!target.isEmpty())
1221                 target += "\n";
1222             do_default = false;
1223             for(QStringList::Iterator wild_it = tmp.begin(); wild_it != tmp.end(); ++wild_it) {
1224                 QString wild = Option::fixPathToTargetOS((*wild_it), false, false);
1225                 QString dirstr = qmake_getpwd(), filestr = wild;
1226                 int slsh = filestr.lastIndexOf(Option::dir_sep);
1227                 if(slsh != -1) {
1228                     dirstr = filestr.left(slsh+1);
1229                     filestr.remove(0, slsh+1);
1230                 }
1231                 if(!dirstr.endsWith(Option::dir_sep))
1232                     dirstr += Option::dir_sep;
1233                 bool is_target = (wild == fileFixify(var("TARGET"), FileFixifyAbsolute));
1234                 if(is_target || exists(wild)) { //real file or target
1235                     QString file = wild;
1236                     QFileInfo fi(fileInfo(wild));
1237                     if(!target.isEmpty())
1238                         target += "\t";
1239                     QString dst_file = filePrefixRoot(root, dst);
1240                     if(fi.isDir() && project->isActiveConfig("copy_dir_files")) {
1241                         if(!dst_file.endsWith(Option::dir_sep))
1242                             dst_file += Option::dir_sep;
1243                         dst_file += fi.fileName();
1244                     }
1245                     QString cmd;
1246                     if (fi.isDir())
1247                        cmd = "-$(INSTALL_DIR)";
1248                     else if (is_target || fi.isExecutable())
1249                        cmd = "-$(INSTALL_PROGRAM)";
1250                     else
1251                        cmd = "-$(INSTALL_FILE)";
1252                     cmd += " " + escapeFilePath(wild) + " " + escapeFilePath(dst_file) + "\n";
1253                     target += cmd;
1254                     if(!project->isActiveConfig("debug") && !project->isActiveConfig("nostrip") &&
1255                        !fi.isDir() && fi.isExecutable() && !project->isEmpty("QMAKE_STRIP"))
1256                         target += QString("\t-") + var("QMAKE_STRIP") + " " +
1257                                   escapeFilePath(filePrefixRoot(root, fileFixify(dst + filestr, FileFixifyAbsolute, false))) + "\n";
1258                     if(!uninst.isEmpty())
1259                         uninst.append("\n\t");
1260                     uninst.append(rm_dir_contents + " " + escapeFilePath(filePrefixRoot(root, fileFixify(dst + filestr, FileFixifyAbsolute, false))));
1261                     continue;
1262                 }
1263                 QString local_dirstr = Option::fixPathToLocalOS(dirstr, true);
1264                 QStringList files = QDir(local_dirstr).entryList(QStringList(filestr));
1265                 const QStringList &installConfigValues = project->values((*it) + ".CONFIG");
1266                 if (installConfigValues.contains("no_check_exist") && files.isEmpty()) {
1267                     if(!target.isEmpty())
1268                         target += "\t";
1269                     QString dst_file = filePrefixRoot(root, dst);
1270                     QString cmd;
1271                     if (installConfigValues.contains("directory")) {
1272                         cmd = QLatin1String("-$(INSTALL_DIR)");
1273                         if (project->isActiveConfig("copy_dir_files")) {
1274                             if (!dst_file.endsWith(Option::dir_sep))
1275                                 dst_file += Option::dir_sep;
1276                             dst_file += filestr;
1277                         }
1278                     } else if (installConfigValues.contains("executable")) {
1279                         cmd = QLatin1String("-$(INSTALL_PROGRAM)");
1280                     } else {
1281                         cmd = QLatin1String("-$(INSTALL_FILE)");
1282                     }
1283                     cmd += " " + escapeFilePath(wild) + " " + escapeFilePath(dst_file) + "\n";
1284                     target += cmd;
1285                     if(!uninst.isEmpty())
1286                         uninst.append("\n\t");
1287                     uninst.append(rm_dir_contents + " " + escapeFilePath(filePrefixRoot(root, fileFixify(dst + filestr, FileFixifyAbsolute, false))));
1288                 }
1289                 for(int x = 0; x < files.count(); x++) {
1290                     QString file = files[x];
1291                     if(file == "." || file == "..") //blah
1292                         continue;
1293                     if(!uninst.isEmpty())
1294                         uninst.append("\n\t");
1295                     uninst.append(rm_dir_contents + " " + escapeFilePath(filePrefixRoot(root, fileFixify(dst + file, FileFixifyAbsolute, false))));
1296                     QFileInfo fi(fileInfo(dirstr + file));
1297                     if(!target.isEmpty())
1298                         target += "\t";
1299                     QString dst_file = filePrefixRoot(root, fileFixify(dst, FileFixifyAbsolute, false));
1300                     if(fi.isDir() && project->isActiveConfig("copy_dir_files")) {
1301                         if(!dst_file.endsWith(Option::dir_sep))
1302                             dst_file += Option::dir_sep;
1303                         dst_file += fi.fileName();
1304                     }
1305                     QString cmd = QString(fi.isDir() ? "-$(INSTALL_DIR)" : "-$(INSTALL_FILE)") + " " +
1306                                   escapeFilePath(dirstr + file) + " " + escapeFilePath(dst_file) + "\n";
1307                     target += cmd;
1308                     if(!project->isActiveConfig("debug") && !project->isActiveConfig("nostrip") &&
1309                        !fi.isDir() && fi.isExecutable() && !project->isEmpty("QMAKE_STRIP"))
1310                         target += QString("\t-") + var("QMAKE_STRIP") + " " +
1311                                   escapeFilePath(filePrefixRoot(root, fileFixify(dst + file, FileFixifyAbsolute, false))) +
1312                                   "\n";
1313                 }
1314             }
1315         }
1316         //default?
1317         if(do_default) {
1318             target = defaultInstall((*it));
1319             uninst = project->values((*it) + ".uninstall");
1320         }
1321
1322         if(!target.isEmpty() || project->values((*it) + ".CONFIG").indexOf("dummy_install") != -1) {
1323             if(noBuild || project->values((*it) + ".CONFIG").indexOf("no_build") != -1)
1324                 t << "install_" << (*it) << ":";
1325             else if(project->isActiveConfig("build_all"))
1326                 t << "install_" << (*it) << ": all";
1327             else
1328                 t << "install_" << (*it) << ": first";
1329             const QStringList &deps = project->values((*it) + ".depends");
1330             if(!deps.isEmpty()) {
1331                 for(QStringList::ConstIterator dep_it = deps.begin(); dep_it != deps.end(); ++dep_it) {
1332                     QString targ = var((*dep_it) + ".target");
1333                     if(targ.isEmpty())
1334                         targ = (*dep_it);
1335                     t << " " << escapeDependencyPath(targ);
1336                 }
1337             }
1338             t << " FORCE\n\t";
1339             const QStringList &dirs = project->values(pvar);
1340             for(QStringList::ConstIterator pit = dirs.begin(); pit != dirs.end(); ++pit) {
1341                 QString tmp_dst = fileFixify((*pit), FileFixifyAbsolute, false);
1342                 if (!isWindowsShell() && !tmp_dst.endsWith(Option::dir_sep))
1343                     tmp_dst += Option::dir_sep;
1344                 t << mkdir_p_asstring(filePrefixRoot(root, tmp_dst)) << "\n\t";
1345             }
1346             t << target << endl << endl;
1347             if(!uninst.isEmpty()) {
1348                 t << "uninstall_" << (*it) << ": FORCE\n\t" << uninst.join(" ")
1349                   << "\n\t-$(DEL_DIR) " << filePrefixRoot(root, dst) << " " << endl << endl;
1350             }
1351             t << endl;
1352
1353             if(project->values((*it) + ".CONFIG").indexOf("no_default_install") == -1) {
1354                 all_installs += QString("install_") + (*it) + " ";
1355                 if(!uninst.isEmpty())
1356                     all_uninstalls += "uninstall_" + (*it) + " ";
1357             }
1358         }   else {
1359             debug_msg(1, "no definition for install %s: install target not created",(*it).toLatin1().constData());
1360         }
1361     }
1362     t << "install: " << var("INSTALLDEPS") << " " << all_installs
1363       << " FORCE\n\nuninstall: " << all_uninstalls << " " << var("UNINSTALLDEPS")
1364       << " FORCE\n\n";
1365 }
1366
1367 QString
1368 MakefileGenerator::var(const QString &var)
1369 {
1370     return val(project->values(var));
1371 }
1372
1373 QString
1374 MakefileGenerator::val(const QStringList &varList)
1375 {
1376     return valGlue(varList, "", " ", "");
1377 }
1378
1379 QString
1380 MakefileGenerator::varGlue(const QString &var, const QString &before, const QString &glue, const QString &after)
1381 {
1382     return valGlue(project->values(var), before, glue, after);
1383 }
1384
1385 QString
1386 MakefileGenerator::fileVarGlue(const QString &var, const QString &before, const QString &glue, const QString &after)
1387 {
1388     QStringList varList;
1389     foreach (const QString &val, project->values(var))
1390         varList << escapeFilePath(Option::fixPathToTargetOS(val));
1391     return valGlue(varList, before, glue, after);
1392 }
1393
1394 QString
1395 MakefileGenerator::valGlue(const QStringList &varList, const QString &before, const QString &glue, const QString &after)
1396 {
1397     QString ret;
1398     for(QStringList::ConstIterator it = varList.begin(); it != varList.end(); ++it) {
1399         if(!(*it).isEmpty()) {
1400             if(!ret.isEmpty())
1401                 ret += glue;
1402             ret += (*it);
1403         }
1404     }
1405     return ret.isEmpty() ? QString("") : before + ret + after;
1406 }
1407
1408
1409 QString
1410 MakefileGenerator::varList(const QString &var)
1411 {
1412     return valList(project->values(var));
1413 }
1414
1415 QString
1416 MakefileGenerator::valList(const QStringList &varList)
1417 {
1418     return valGlue(varList, "", " \\\n\t\t", "");
1419 }
1420
1421 QStringList
1422 MakefileGenerator::createObjectList(const QStringList &sources)
1423 {
1424     QStringList ret;
1425     QString objdir;
1426     if(!project->values("OBJECTS_DIR").isEmpty())
1427         objdir = project->first("OBJECTS_DIR");
1428     for(QStringList::ConstIterator it = sources.begin(); it != sources.end(); ++it) {
1429         QFileInfo fi(fileInfo(Option::fixPathToLocalOS((*it))));
1430         QString dir;
1431         if(objdir.isEmpty() && project->isActiveConfig("object_with_source")) {
1432             QString fName = Option::fixPathToTargetOS((*it), false);
1433             int dl = fName.lastIndexOf(Option::dir_sep);
1434             if(dl != -1)
1435                 dir = fName.left(dl + 1);
1436         } else if (project->isActiveConfig("object_parallel_to_source")) {
1437             // The source paths are relative to the output dir, but we need source-relative paths
1438             QString sourceRelativePath = fileFixify(*it, qmake_getpwd(), Option::output_dir);
1439             sourceRelativePath = Option::fixPathToTargetOS(sourceRelativePath, false);
1440
1441             if (sourceRelativePath.startsWith(".." + Option::dir_sep))
1442                 sourceRelativePath = fileFixify(sourceRelativePath, FileFixifyAbsolute);
1443
1444             if (QDir::isAbsolutePath(sourceRelativePath))
1445                 sourceRelativePath.remove(0, sourceRelativePath.indexOf(Option::dir_sep) + 1);
1446
1447             dir = objdir; // We still respect OBJECTS_DIR
1448
1449             int lastDirSepPosition = sourceRelativePath.lastIndexOf(Option::dir_sep);
1450             if (lastDirSepPosition != -1)
1451                 dir += sourceRelativePath.leftRef(lastDirSepPosition + 1);
1452
1453             if (!noIO()) {
1454                 // Ensure that the final output directory of each object exists
1455                 QString outRelativePath = fileFixify(dir, qmake_getpwd(), Option::output_dir);
1456                 if (!mkdir(outRelativePath))
1457                     warn_msg(WarnLogic, "Cannot create directory '%s'", outRelativePath.toLatin1().constData());
1458             }
1459         } else {
1460             dir = objdir;
1461         }
1462         ret.append(dir + fi.completeBaseName() + Option::obj_ext);
1463     }
1464     return ret;
1465 }
1466
1467 ReplaceExtraCompilerCacheKey::ReplaceExtraCompilerCacheKey(const QString &v, const QStringList &i, const QStringList &o)
1468 {
1469     static QString doubleColon = QLatin1String("::");
1470
1471     hash = 0;
1472     pwd = qmake_getpwd();
1473     var = v;
1474     {
1475         QStringList il = i;
1476         il.sort();
1477         in = il.join(doubleColon);
1478     }
1479     {
1480         QStringList ol = o;
1481         ol.sort();
1482         out = ol.join(doubleColon);
1483     }
1484 }
1485
1486 bool ReplaceExtraCompilerCacheKey::operator==(const ReplaceExtraCompilerCacheKey &f) const
1487 {
1488     return (hashCode() == f.hashCode() &&
1489             f.in == in &&
1490             f.out == out &&
1491             f.var == var &&
1492             f.pwd == pwd);
1493 }
1494
1495
1496 QString
1497 MakefileGenerator::replaceExtraCompilerVariables(const QString &orig_var, const QStringList &in, const QStringList &out)
1498 {
1499     //lazy cache
1500     ReplaceExtraCompilerCacheKey cacheKey(orig_var, in, out);
1501     QString cacheVal = extraCompilerVariablesCache.value(cacheKey);
1502     if(!cacheVal.isNull())
1503         return cacheVal;
1504
1505     //do the work
1506     QString ret = orig_var;
1507     QRegExp reg_var("\\$\\{.*\\}");
1508     reg_var.setMinimal(true);
1509     for(int rep = 0; (rep = reg_var.indexIn(ret, rep)) != -1; ) {
1510         QStringList val;
1511         const QString var = ret.mid(rep + 2, reg_var.matchedLength() - 3);
1512         bool filePath = false;
1513         if(val.isEmpty() && var.startsWith(QLatin1String("QMAKE_VAR_"))) {
1514             const QString varname = var.mid(10);
1515             val += project->values(varname);
1516         }
1517         if(val.isEmpty() && var.startsWith(QLatin1String("QMAKE_VAR_FIRST_"))) {
1518             const QString varname = var.mid(16);
1519             val += project->first(varname);
1520         }
1521
1522         if(val.isEmpty() && !in.isEmpty()) {
1523             if(var.startsWith(QLatin1String("QMAKE_FUNC_FILE_IN_"))) {
1524                 filePath = true;
1525                 const QString funcname = var.mid(19);
1526                 val += project->expand(funcname, QList<QStringList>() << in);
1527             } else if(var == QLatin1String("QMAKE_FILE_BASE") || var == QLatin1String("QMAKE_FILE_IN_BASE")) {
1528                 //filePath = true;
1529                 for(int i = 0; i < in.size(); ++i) {
1530                     QFileInfo fi(fileInfo(Option::fixPathToLocalOS(in.at(i))));
1531                     QString base = fi.completeBaseName();
1532                     if(base.isNull())
1533                         base = fi.fileName();
1534                     val += base;
1535                 }
1536             } else if(var == QLatin1String("QMAKE_FILE_EXT")) {
1537                 filePath = true;
1538                 for(int i = 0; i < in.size(); ++i) {
1539                     QFileInfo fi(fileInfo(Option::fixPathToLocalOS(in.at(i))));
1540                     QString ext;
1541                     // Ensure complementarity with QMAKE_FILE_BASE
1542                     int baseLen = fi.completeBaseName().length();
1543                     if(baseLen == 0)
1544                         ext = fi.fileName();
1545                     else
1546                         ext = fi.fileName().remove(0, baseLen);
1547                     val += ext;
1548                 }
1549             } else if(var == QLatin1String("QMAKE_FILE_PATH") || var == QLatin1String("QMAKE_FILE_IN_PATH")) {
1550                 filePath = true;
1551                 for(int i = 0; i < in.size(); ++i)
1552                     val += fileInfo(Option::fixPathToLocalOS(in.at(i))).path();
1553             } else if(var == QLatin1String("QMAKE_FILE_NAME") || var == QLatin1String("QMAKE_FILE_IN")) {
1554                 filePath = true;
1555                 for(int i = 0; i < in.size(); ++i)
1556                     val += fileInfo(Option::fixPathToLocalOS(in.at(i))).filePath();
1557
1558             }
1559         }
1560         if(val.isEmpty() && !out.isEmpty()) {
1561             if(var.startsWith(QLatin1String("QMAKE_FUNC_FILE_OUT_"))) {
1562                 filePath = true;
1563                 const QString funcname = var.mid(20);
1564                 val += project->expand(funcname, QList<QStringList>() << out);
1565             } else if(var == QLatin1String("QMAKE_FILE_OUT")) {
1566                 filePath = true;
1567                 for(int i = 0; i < out.size(); ++i)
1568                     val += fileInfo(Option::fixPathToLocalOS(out.at(i))).filePath();
1569             } else if(var == QLatin1String("QMAKE_FILE_OUT_BASE")) {
1570                 //filePath = true;
1571                 for(int i = 0; i < out.size(); ++i) {
1572                     QFileInfo fi(fileInfo(Option::fixPathToLocalOS(out.at(i))));
1573                     QString base = fi.completeBaseName();
1574                     if(base.isNull())
1575                         base = fi.fileName();
1576                     val += base;
1577                 }
1578             }
1579         }
1580         if(val.isEmpty() && var.startsWith(QLatin1String("QMAKE_FUNC_"))) {
1581             const QString funcname = var.mid(11);
1582             val += project->expand(funcname, QList<QStringList>() << in << out);
1583         }
1584
1585         if(!val.isEmpty()) {
1586             QString fullVal;
1587             if(filePath) {
1588                 for(int i = 0; i < val.size(); ++i) {
1589                     const QString file = Option::fixPathToTargetOS(unescapeFilePath(val.at(i)), false);
1590                     if(!fullVal.isEmpty())
1591                         fullVal += " ";
1592                     fullVal += escapeFilePath(file);
1593                 }
1594             } else {
1595                 fullVal = val.join(" ");
1596             }
1597             ret.replace(rep, reg_var.matchedLength(), fullVal);
1598             rep += fullVal.length();
1599         } else {
1600             rep += reg_var.matchedLength();
1601         }
1602     }
1603
1604     //cache the value
1605     extraCompilerVariablesCache.insert(cacheKey, ret);
1606     return ret;
1607 }
1608
1609 bool
1610 MakefileGenerator::verifyExtraCompiler(const QString &comp, const QString &file_unfixed)
1611 {
1612     if(noIO())
1613         return false;
1614     const QString file = Option::fixPathToLocalOS(file_unfixed);
1615
1616     if(project->values(comp + ".CONFIG").indexOf("moc_verify") != -1) {
1617         if(!file.isNull()) {
1618             QMakeSourceFileInfo::addSourceFile(file, QMakeSourceFileInfo::SEEK_MOCS);
1619             if(!mocable(file)) {
1620                 return false;
1621             } else {
1622                 project->values("MOCABLES").append(file);
1623             }
1624         }
1625     } else if(project->values(comp + ".CONFIG").indexOf("function_verify") != -1) {
1626         QString tmp_out = project->values(comp + ".output").first();
1627         if(tmp_out.isEmpty())
1628             return false;
1629         QStringList verify_function = project->values(comp + ".verify_function");
1630         if(verify_function.isEmpty())
1631             return false;
1632
1633         for(int i = 0; i < verify_function.size(); ++i) {
1634             bool invert = false;
1635             QString verify = verify_function.at(i);
1636             if(verify.at(0) == QLatin1Char('!')) {
1637                 invert = true;
1638                 verify = verify.mid(1);
1639             }
1640
1641             if(project->values(comp + ".CONFIG").indexOf("combine") != -1) {
1642                 bool pass = project->test(verify, QList<QStringList>() << QStringList(tmp_out) << QStringList(file));
1643                 if(invert)
1644                     pass = !pass;
1645                 if(!pass)
1646                     return false;
1647             } else {
1648                 const QStringList &tmp = project->values(comp + ".input");
1649                 for (QStringList::ConstIterator it = tmp.begin(); it != tmp.end(); ++it) {
1650                     const QStringList &inputs = project->values((*it));
1651                     for (QStringList::ConstIterator input = inputs.begin(); input != inputs.end(); ++input) {
1652                         if((*input).isEmpty())
1653                             continue;
1654                         QString in = fileFixify(Option::fixPathToTargetOS((*input), false));
1655                         if(in == file) {
1656                             bool pass = project->test(verify,
1657                                                       QList<QStringList>() << QStringList(replaceExtraCompilerVariables(tmp_out, (*input), QString())) <<
1658                                                       QStringList(file));
1659                             if(invert)
1660                                 pass = !pass;
1661                             if(!pass)
1662                                 return false;
1663                             break;
1664                         }
1665                     }
1666                 }
1667             }
1668         }
1669     } else if(project->values(comp + ".CONFIG").indexOf("verify") != -1) {
1670         QString tmp_out = project->values(comp + ".output").first();
1671         if(tmp_out.isEmpty())
1672             return false;
1673         QString tmp_cmd;
1674         if(!project->isEmpty(comp + ".commands")) {
1675             int argv0 = -1;
1676             QStringList cmdline = project->values(comp + ".commands");
1677             for(int i = 0; i < cmdline.count(); ++i) {
1678                 if(!cmdline.at(i).contains('=')) {
1679                     argv0 = i;
1680                     break;
1681                 }
1682             }
1683             if(argv0 != -1) {
1684                 cmdline[argv0] = Option::fixPathToTargetOS(cmdline.at(argv0), false);
1685                 tmp_cmd = cmdline.join(" ");
1686             }
1687         }
1688
1689         if(project->values(comp + ".CONFIG").indexOf("combine") != -1) {
1690             QString cmd = replaceExtraCompilerVariables(tmp_cmd, QString(), tmp_out);
1691             if(system(cmd.toLatin1().constData()))
1692                 return false;
1693         } else {
1694             const QStringList &tmp = project->values(comp + ".input");
1695             for (QStringList::ConstIterator it = tmp.begin(); it != tmp.end(); ++it) {
1696                 const QStringList &inputs = project->values((*it));
1697                 for (QStringList::ConstIterator input = inputs.begin(); input != inputs.end(); ++input) {
1698                     if((*input).isEmpty())
1699                         continue;
1700                     QString in = fileFixify(Option::fixPathToTargetOS((*input), false));
1701                     if(in == file) {
1702                         QString out = replaceExtraCompilerVariables(tmp_out, (*input), QString());
1703                         QString cmd = replaceExtraCompilerVariables(tmp_cmd, in, out);
1704                         if(system(cmd.toLatin1().constData()))
1705                             return false;
1706                         break;
1707                     }
1708                 }
1709             }
1710         }
1711     }
1712     return true;
1713 }
1714
1715 void
1716 MakefileGenerator::writeExtraTargets(QTextStream &t)
1717 {
1718     const QStringList &qut = project->values("QMAKE_EXTRA_TARGETS");
1719     for (QStringList::ConstIterator it = qut.begin(); it != qut.end(); ++it) {
1720         QString targ = var((*it) + ".target"),
1721                  cmd = var((*it) + ".commands"), deps;
1722         if(targ.isEmpty())
1723             targ = (*it);
1724         const QStringList &deplist = project->values((*it) + ".depends");
1725         for (QStringList::ConstIterator dep_it = deplist.begin(); dep_it != deplist.end(); ++dep_it) {
1726             QString dep = var((*dep_it) + ".target");
1727             if(dep.isEmpty())
1728                 dep = (*dep_it);
1729             deps += " " + escapeDependencyPath(dep);
1730         }
1731         if(project->values((*it) + ".CONFIG").indexOf("fix_target") != -1)
1732             targ = fileFixify(targ, Option::output_dir, Option::output_dir);
1733         if (project->values((*it) + ".CONFIG").indexOf("phony") != -1)
1734             deps += QLatin1String(" FORCE");
1735         t << escapeDependencyPath(targ) << ":" << deps;
1736         if(!cmd.isEmpty())
1737             t << "\n\t" << cmd;
1738         t << endl << endl;
1739     }
1740 }
1741
1742 void
1743 MakefileGenerator::writeExtraCompilerTargets(QTextStream &t)
1744 {
1745     QString clean_targets;
1746     const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
1747     for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
1748         QString tmp_out = fileFixify(project->values((*it) + ".output").first(),
1749                                      Option::output_dir, Option::output_dir);
1750         QString tmp_cmd;
1751         if(!project->isEmpty((*it) + ".commands")) {
1752             QStringList cmdline = project->values((*it) + ".commands");
1753             int argv0 = findExecutable(cmdline);
1754             if(argv0 != -1) {
1755                 cmdline[argv0] = escapeFilePath(Option::fixPathToTargetOS(cmdline.at(argv0), false));
1756                 tmp_cmd = cmdline.join(" ");
1757             }
1758         }
1759         QStringList tmp_dep = project->values((*it) + ".depends");
1760         QString tmp_dep_cmd;
1761         QString dep_cd_cmd;
1762         if(!project->isEmpty((*it) + ".depend_command")) {
1763             int argv0 = -1;
1764             QStringList cmdline = project->values((*it) + ".depend_command");
1765             for(int i = 0; i < cmdline.count(); ++i) {
1766                 if(!cmdline.at(i).contains('=')) {
1767                     argv0 = i;
1768                     break;
1769                 }
1770             }
1771             if(argv0 != -1) {
1772                 const QString c = Option::fixPathToLocalOS(cmdline.at(argv0), true);
1773                 if(exists(c)) {
1774                     cmdline[argv0] = escapeFilePath(Option::fixPathToLocalOS(cmdline.at(argv0), false));
1775                 } else {
1776                     cmdline[argv0] = escapeFilePath(cmdline.at(argv0));
1777                 }
1778                 QFileInfo cmdFileInfo(cmdline[argv0]);
1779                 if (!cmdFileInfo.isAbsolute() || cmdFileInfo.exists())
1780                     tmp_dep_cmd = cmdline.join(" ");
1781             }
1782             dep_cd_cmd = QLatin1String("cd ")
1783                  + escapeFilePath(Option::fixPathToLocalOS(Option::output_dir, false))
1784                  + QLatin1String(" && ");
1785         }
1786         const QStringList &vars = project->values((*it) + ".variables");
1787         if(tmp_out.isEmpty() || tmp_cmd.isEmpty())
1788             continue;
1789         QStringList tmp_inputs;
1790         {
1791             const QStringList &comp_inputs = project->values((*it) + ".input");
1792             for(QStringList::ConstIterator it2 = comp_inputs.begin(); it2 != comp_inputs.end(); ++it2) {
1793                 const QStringList &tmp = project->values((*it2));
1794                 for(QStringList::ConstIterator input = tmp.begin(); input != tmp.end(); ++input) {
1795                     QString in = Option::fixPathToTargetOS((*input), false);
1796                     if(verifyExtraCompiler((*it), in))
1797                         tmp_inputs.append((*input));
1798                 }
1799             }
1800         }
1801
1802         t << "compiler_" << (*it) << "_make_all:";
1803         if(project->values((*it) + ".CONFIG").indexOf("combine") != -1) {
1804             // compilers with a combined input only have one output
1805             QString input = project->values((*it) + ".output").first();
1806             t << " " << escapeDependencyPath(replaceExtraCompilerVariables(tmp_out, input, QString()));
1807         } else {
1808             for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input) {
1809                 QString in = Option::fixPathToTargetOS((*input), false);
1810                 t << " " << escapeDependencyPath(replaceExtraCompilerVariables(tmp_out, (*input), QString()));
1811             }
1812         }
1813         t << endl;
1814
1815         if(project->values((*it) + ".CONFIG").indexOf("no_clean") == -1) {
1816             QString tmp_clean = project->values((*it) + ".clean").join(" ");
1817             QString tmp_clean_cmds = project->values((*it) + ".clean_commands").join(" ");
1818             if(!tmp_inputs.isEmpty())
1819                 clean_targets += QString("compiler_" + (*it) + "_clean ");
1820             t << "compiler_" << (*it) << "_clean:";
1821             bool wrote_clean_cmds = false, wrote_clean = false;
1822             if(tmp_clean_cmds.isEmpty()) {
1823                 wrote_clean_cmds = true;
1824             } else if(tmp_clean_cmds.indexOf("${QMAKE_") == -1) {
1825                 t << "\n\t" << tmp_clean_cmds;
1826                 wrote_clean_cmds = true;
1827             }
1828             if(tmp_clean.isEmpty())
1829                 tmp_clean = tmp_out;
1830             if(tmp_clean.indexOf("${QMAKE_") == -1) {
1831                 t << "\n\t" << "-$(DEL_FILE) " << tmp_clean;
1832                 wrote_clean = true;
1833             }
1834             if(!wrote_clean_cmds || !wrote_clean) {
1835                 QStringList cleans;
1836                 const QString del_statement("-$(DEL_FILE)");
1837                 if(!wrote_clean) {
1838                     if(project->isActiveConfig("no_delete_multiple_files")) {
1839                         for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input)
1840                             cleans.append(" " + replaceExtraCompilerVariables(tmp_clean, (*input),
1841                                                 replaceExtraCompilerVariables(tmp_out, (*input), QString())));
1842                     } else {
1843                         QString files, file;
1844                         const int commandlineLimit = 2047; // NT limit, expanded
1845                         for(int input = 0; input < tmp_inputs.size(); ++input) {
1846                             file = " " + replaceExtraCompilerVariables(tmp_clean, tmp_inputs.at(input),
1847                                            replaceExtraCompilerVariables(tmp_out, tmp_inputs.at(input), QString()));
1848                             if(del_statement.length() + files.length() +
1849                                qMax(fixEnvVariables(file).length(), file.length()) > commandlineLimit) {
1850                                 cleans.append(files);
1851                                 files.clear();
1852                             }
1853                             files += file;
1854                         }
1855                         if(!files.isEmpty())
1856                             cleans.append(files);
1857                     }
1858                 }
1859                 if(!cleans.isEmpty())
1860                     t << valGlue(cleans, "\n\t" + del_statement, "\n\t" + del_statement, "");
1861                 if(!wrote_clean_cmds) {
1862                     for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input) {
1863                         t << "\n\t" << replaceExtraCompilerVariables(tmp_clean_cmds, (*input),
1864                                          replaceExtraCompilerVariables(tmp_out, (*input), QString()));
1865                     }
1866                 }
1867             }
1868             t << endl;
1869         }
1870         if(project->values((*it) + ".CONFIG").indexOf("combine") != -1) {
1871             if(tmp_out.indexOf("${QMAKE_") != -1) {
1872                 warn_msg(WarnLogic, "QMAKE_EXTRA_COMPILERS(%s) with combine has variable output.",
1873                          (*it).toLatin1().constData());
1874                 continue;
1875             }
1876             QStringList deps, inputs;
1877             if(!tmp_dep.isEmpty())
1878                 deps += fileFixify(tmp_dep, Option::output_dir, Option::output_dir);
1879             for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input) {
1880                 deps += findDependencies((*input));
1881                 inputs += Option::fixPathToTargetOS((*input), false);
1882                 if(!tmp_dep_cmd.isEmpty() && doDepends()) {
1883                     char buff[256];
1884                     QString dep_cmd = replaceExtraCompilerVariables(tmp_dep_cmd, (*input),
1885                                                                     tmp_out);
1886                     dep_cmd = dep_cd_cmd + fixEnvVariables(dep_cmd);
1887                     if(FILE *proc = QT_POPEN(dep_cmd.toLatin1().constData(), "r")) {
1888                         QString indeps;
1889                         while(!feof(proc)) {
1890                             int read_in = (int)fread(buff, 1, 255, proc);
1891                             if(!read_in)
1892                                 break;
1893                             indeps += QByteArray(buff, read_in);
1894                         }
1895                         QT_PCLOSE(proc);
1896                         if(!indeps.isEmpty()) {
1897                             QStringList dep_cmd_deps = indeps.replace('\n', ' ').simplified().split(' ');
1898                             for(int i = 0; i < dep_cmd_deps.count(); ++i) {
1899                                 QString &file = dep_cmd_deps[i];
1900                                 if(!exists(file)) {
1901                                     QString localFile;
1902                                     QList<QMakeLocalFileName> depdirs = QMakeSourceFileInfo::dependencyPaths();
1903                                     for(QList<QMakeLocalFileName>::Iterator it = depdirs.begin();
1904                                         it != depdirs.end(); ++it) {
1905                                         if(exists((*it).real() + Option::dir_sep + file)) {
1906                                             localFile = (*it).local() + Option::dir_sep + file;
1907                                             break;
1908                                         }
1909                                     }
1910                                     file = localFile;
1911                                 }
1912                                 if(!file.isEmpty())
1913                                     file = fileFixify(file);
1914                             }
1915                             deps += dep_cmd_deps;
1916                         }
1917                     }
1918                 }
1919             }
1920             for(int i = 0; i < inputs.size(); ) {
1921                 if(tmp_out == inputs.at(i))
1922                     inputs.removeAt(i);
1923                 else
1924                     ++i;
1925             }
1926             for(int i = 0; i < deps.size(); ) {
1927                 if(tmp_out == deps.at(i))
1928                     deps.removeAt(i);
1929                 else
1930                     ++i;
1931             }
1932             if (inputs.isEmpty())
1933                 continue;
1934
1935             QString cmd = replaceExtraCompilerVariables(tmp_cmd, escapeFilePaths(inputs), QStringList(tmp_out));
1936             t << escapeDependencyPath(tmp_out) << ":";
1937             // compiler.CONFIG+=explicit_dependencies means that ONLY compiler.depends gets to cause Makefile dependencies
1938             if(project->values((*it) + ".CONFIG").indexOf("explicit_dependencies") != -1) {
1939                 t << " " << valList(escapeDependencyPaths(fileFixify(tmp_dep, Option::output_dir, Option::output_dir)));
1940             } else {
1941                 t << " " << valList(escapeDependencyPaths(inputs)) << " " << valList(escapeDependencyPaths(deps));
1942             }
1943             t << "\n\t" << cmd << endl << endl;
1944             continue;
1945         }
1946         for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input) {
1947             QString in = Option::fixPathToTargetOS((*input), false);
1948             QStringList deps = findDependencies((*input));
1949             deps += escapeDependencyPath(in);
1950             QString out = replaceExtraCompilerVariables(tmp_out, (*input), QString());
1951             if(!tmp_dep.isEmpty()) {
1952                 QStringList pre_deps = fileFixify(tmp_dep, Option::output_dir, Option::output_dir);
1953                 for(int i = 0; i < pre_deps.size(); ++i)
1954                    deps += replaceExtraCompilerVariables(pre_deps.at(i), (*input), out);
1955             }
1956             QString cmd = replaceExtraCompilerVariables(tmp_cmd, (*input), out);
1957             // NOTE: The var -> QMAKE_COMP_var replace feature is unsupported, do not use!
1958             for(QStringList::ConstIterator it3 = vars.constBegin(); it3 != vars.constEnd(); ++it3)
1959                 cmd.replace("$(" + (*it3) + ")", "$(QMAKE_COMP_" + (*it3)+")");
1960             if(!tmp_dep_cmd.isEmpty() && doDepends()) {
1961                 char buff[256];
1962                 QString dep_cmd = replaceExtraCompilerVariables(tmp_dep_cmd, (*input), out);
1963                 dep_cmd = dep_cd_cmd + fixEnvVariables(dep_cmd);
1964                 if(FILE *proc = QT_POPEN(dep_cmd.toLatin1().constData(), "r")) {
1965                     QString indeps;
1966                     while(!feof(proc)) {
1967                         int read_in = (int)fread(buff, 1, 255, proc);
1968                         if(!read_in)
1969                             break;
1970                         indeps += QByteArray(buff, read_in);
1971                     }
1972                     QT_PCLOSE(proc);
1973                     if(!indeps.isEmpty()) {
1974                         QStringList dep_cmd_deps = indeps.replace('\n', ' ').simplified().split(' ');
1975                         for(int i = 0; i < dep_cmd_deps.count(); ++i) {
1976                             QString &file = dep_cmd_deps[i];
1977                             if(!exists(file)) {
1978                                 QString localFile;
1979                                 QList<QMakeLocalFileName> depdirs = QMakeSourceFileInfo::dependencyPaths();
1980                                 for(QList<QMakeLocalFileName>::Iterator it = depdirs.begin();
1981                                     it != depdirs.end(); ++it) {
1982                                     if(exists((*it).real() + Option::dir_sep + file)) {
1983                                         localFile = (*it).local() + Option::dir_sep + file;
1984                                         break;
1985                                     }
1986                                 }
1987                                 file = localFile;
1988                             }
1989                             if(!file.isEmpty())
1990                                 file = fileFixify(file);
1991                         }
1992                         deps += dep_cmd_deps;
1993                     }
1994                 }
1995                 //use the depend system to find includes of these included files
1996                 QStringList inc_deps;
1997                 for(int i = 0; i < deps.size(); ++i) {
1998                     const QString dep = deps.at(i);
1999                     if(QFile::exists(dep)) {
2000                         SourceFileType type = TYPE_UNKNOWN;
2001                         if(type == TYPE_UNKNOWN) {
2002                             for(QStringList::Iterator cit = Option::c_ext.begin();
2003                                 cit != Option::c_ext.end(); ++cit) {
2004                                 if(dep.endsWith((*cit))) {
2005                                    type = TYPE_C;
2006                                    break;
2007                                 }
2008                             }
2009                         }
2010                         if(type == TYPE_UNKNOWN) {
2011                             for(QStringList::Iterator cppit = Option::cpp_ext.begin();
2012                                 cppit != Option::cpp_ext.end(); ++cppit) {
2013                                 if(dep.endsWith((*cppit))) {
2014                                     type = TYPE_C;
2015                                     break;
2016                                 }
2017                             }
2018                         }
2019                         if(type == TYPE_UNKNOWN) {
2020                             for(QStringList::Iterator hit = Option::h_ext.begin();
2021                                 type == TYPE_UNKNOWN && hit != Option::h_ext.end(); ++hit) {
2022                                 if(dep.endsWith((*hit))) {
2023                                     type = TYPE_C;
2024                                     break;
2025                                 }
2026                             }
2027                         }
2028                         if(type != TYPE_UNKNOWN) {
2029                             if(!QMakeSourceFileInfo::containsSourceFile(dep, type))
2030                                 QMakeSourceFileInfo::addSourceFile(dep, type);
2031                             inc_deps += QMakeSourceFileInfo::dependencies(dep);
2032                         }
2033                     }
2034                 }
2035                 deps += inc_deps;
2036             }
2037             for(int i = 0; i < deps.size(); ) {
2038                 QString &dep = deps[i];
2039                 dep = Option::fixPathToTargetOS(unescapeFilePath(dep), false);
2040                 if(out == dep)
2041                     deps.removeAt(i);
2042                 else
2043                     ++i;
2044             }
2045             t << escapeDependencyPath(out) << ": " << valList(escapeDependencyPaths(deps)) << "\n\t"
2046               << cmd << endl << endl;
2047         }
2048     }
2049     t << "compiler_clean: " << clean_targets << endl << endl;
2050 }
2051
2052 void
2053 MakefileGenerator::writeExtraCompilerVariables(QTextStream &t)
2054 {
2055     bool first = true;
2056     const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
2057     for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
2058         const QStringList &vars = project->values((*it) + ".variables");
2059         for(QStringList::ConstIterator varit = vars.begin(); varit != vars.end(); ++varit) {
2060             if(first) {
2061                 t << "\n####### Custom Compiler Variables" << endl;
2062                 first = false;
2063             }
2064             t << "QMAKE_COMP_" << (*varit) << " = "
2065               << valList(project->values((*varit))) << endl;
2066         }
2067     }
2068     if(!first)
2069         t << endl;
2070 }
2071
2072 void
2073 MakefileGenerator::writeExtraVariables(QTextStream &t)
2074 {
2075     t << endl;
2076
2077     QStringList outlist;
2078     const QHash<QString, QStringList> &vars = project->variables();
2079     const QStringList &exports = project->values("QMAKE_EXTRA_VARIABLES");
2080     for (QHash<QString, QStringList>::ConstIterator it = vars.begin(); it != vars.end(); ++it) {
2081         for (QStringList::ConstIterator exp_it = exports.begin(); exp_it != exports.end(); ++exp_it) {
2082             QRegExp rx((*exp_it), Qt::CaseInsensitive, QRegExp::Wildcard);
2083             if (rx.exactMatch(it.key()))
2084                 outlist << ("EXPORT_" + it.key() + " = " + it.value().join(" "));
2085         }
2086     }
2087     if (!outlist.isEmpty()) {
2088         t << "####### Custom Variables" << endl;
2089         t << outlist.join("\n") << endl << endl;
2090     }
2091 }
2092
2093 bool
2094 MakefileGenerator::writeStubMakefile(QTextStream &t)
2095 {
2096     t << "QMAKE    = " << var("QMAKE_QMAKE") << endl;
2097     const QStringList &qut = project->values("QMAKE_EXTRA_TARGETS");
2098     for(QStringList::ConstIterator it = qut.begin(); it != qut.end(); ++it)
2099         t << *it << " ";
2100     //const QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
2101     t << "first all clean install distclean uninstall: " << "qmake" << endl
2102       << "qmake_all:" << endl;
2103     writeMakeQmake(t);
2104     t << "FORCE:" << endl << endl;
2105     return true;
2106 }
2107
2108 bool
2109 MakefileGenerator::writeMakefile(QTextStream &t)
2110 {
2111     t << "####### Compile" << endl << endl;
2112     writeObj(t, "SOURCES");
2113     writeObj(t, "GENERATED_SOURCES");
2114
2115     t << "####### Install" << endl << endl;
2116     writeInstalls(t, "INSTALLS");
2117
2118     t << "FORCE:" << endl << endl;
2119     return true;
2120 }
2121
2122 QString MakefileGenerator::fixifySpecdir(const QString &spec, const QString &outdir)
2123 {
2124     if (QFileInfo(spec).isAbsolute())
2125         return fileFixify(spec, outdir);
2126     return spec;
2127 }
2128
2129 QString MakefileGenerator::buildArgs(const QString &outdir)
2130 {
2131     QString ret;
2132     //special variables
2133     if(!project->isEmpty("QMAKE_ABSOLUTE_SOURCE_PATH"))
2134         ret += " QMAKE_ABSOLUTE_SOURCE_PATH=" + escapeFilePath(project->first("QMAKE_ABSOLUTE_SOURCE_PATH"));
2135
2136     //warnings
2137     else if(Option::warn_level == WarnNone)
2138         ret += " -Wnone";
2139     else if(Option::warn_level == WarnAll)
2140         ret += " -Wall";
2141     else if(Option::warn_level & WarnParser)
2142         ret += " -Wparser";
2143     //other options
2144     if(!Option::user_template.isEmpty())
2145         ret += " -t " + Option::user_template;
2146     if(!Option::user_template_prefix.isEmpty())
2147         ret += " -tp " + Option::user_template_prefix;
2148     if(!Option::mkfile::do_cache)
2149         ret += " -nocache";
2150     if(!Option::mkfile::do_deps)
2151         ret += " -nodepend";
2152     if(!Option::mkfile::do_dep_heuristics)
2153         ret += " -nodependheuristics";
2154     if(!Option::mkfile::qmakespec_commandline.isEmpty())
2155         ret += " -spec " + fixifySpecdir(Option::mkfile::qmakespec, outdir);
2156     if (!Option::mkfile::xqmakespec_commandline.isEmpty())
2157         ret += " -xspec " + fixifySpecdir(Option::mkfile::xqmakespec, outdir);
2158
2159     //arguments
2160     for(QStringList::Iterator it = Option::before_user_vars.begin();
2161         it != Option::before_user_vars.end(); ++it) {
2162         if((*it).left(qstrlen("QMAKE_ABSOLUTE_SOURCE_PATH")) != "QMAKE_ABSOLUTE_SOURCE_PATH")
2163             ret += " " + escapeFilePath((*it));
2164     }
2165     if(Option::after_user_vars.count()) {
2166         ret += " -after ";
2167         for(QStringList::Iterator it = Option::after_user_vars.begin();
2168             it != Option::after_user_vars.end(); ++it) {
2169             if((*it).left(qstrlen("QMAKE_ABSOLUTE_SOURCE_PATH")) != "QMAKE_ABSOLUTE_SOURCE_PATH")
2170                 ret += " " + escapeFilePath((*it));
2171         }
2172     }
2173     return ret;
2174 }
2175
2176 //could get stored argv, but then it would have more options than are
2177 //probably necesary this will try to guess the bare minimum..
2178 QString MakefileGenerator::build_args(const QString &outdir)
2179 {
2180     QString ret = "$(QMAKE)";
2181
2182     // general options and arguments
2183     ret += buildArgs(outdir);
2184
2185     //output
2186     QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
2187     if(!ofile.isEmpty() && ofile != project->first("QMAKE_MAKEFILE"))
2188         ret += " -o " + escapeFilePath(ofile);
2189
2190     //inputs
2191     ret += " " + escapeFilePath(fileFixify(project->projectFile(), outdir));
2192
2193     return ret;
2194 }
2195
2196 void
2197 MakefileGenerator::writeHeader(QTextStream &t)
2198 {
2199     t << "#############################################################################" << endl;
2200     t << "# Makefile for building: " << escapeFilePath(var("TARGET")) << endl;
2201     t << "# Generated by qmake (" << qmake_version() << ") (Qt " << QT_VERSION_STR << ") on: ";
2202     t << QDateTime::currentDateTime().toString() << endl;
2203     t << "# Project:  " << fileFixify(project->projectFile()) << endl;
2204     t << "# Template: " << var("TEMPLATE") << endl;
2205     if(!project->isActiveConfig("build_pass"))
2206         t << "# Command: " << build_args().replace("$(QMAKE)", var("QMAKE_QMAKE")) << endl;
2207     t << "#############################################################################" << endl;
2208     t << endl;
2209 }
2210
2211 QList<MakefileGenerator::SubTarget*>
2212 MakefileGenerator::findSubDirsSubTargets() const
2213 {
2214     QList<SubTarget*> targets;
2215     {
2216         const QStringList subdirs = project->values("SUBDIRS");
2217         for(int subdir = 0; subdir < subdirs.size(); ++subdir) {
2218             QString fixedSubdir = subdirs[subdir];
2219             fixedSubdir = fixedSubdir.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2220
2221             SubTarget *st = new SubTarget;
2222             st->name = subdirs[subdir];
2223             targets.append(st);
2224
2225             bool fromFile = false;
2226             QString file = subdirs[subdir];
2227             if(!project->isEmpty(fixedSubdir + ".file")) {
2228                 if(!project->isEmpty(fixedSubdir + ".subdir"))
2229                     warn_msg(WarnLogic, "Cannot assign both file and subdir for subdir %s",
2230                              subdirs[subdir].toLatin1().constData());
2231                 file = project->first(fixedSubdir + ".file");
2232                 fromFile = true;
2233             } else if(!project->isEmpty(fixedSubdir + ".subdir")) {
2234                 file = project->first(fixedSubdir + ".subdir");
2235                 fromFile = false;
2236             } else {
2237                 fromFile = file.endsWith(Option::pro_ext);
2238             }
2239             file = Option::fixPathToTargetOS(file);
2240
2241             if(fromFile) {
2242                 int slsh = file.lastIndexOf(Option::dir_sep);
2243                 if(slsh != -1) {
2244                     st->in_directory = file.left(slsh+1);
2245                     st->profile = file.mid(slsh+1);
2246                 } else {
2247                     st->profile = file;
2248                 }
2249             } else {
2250                 if(!file.isEmpty() && !project->isActiveConfig("subdir_first_pro"))
2251                     st->profile = file.section(Option::dir_sep, -1) + Option::pro_ext;
2252                 st->in_directory = file;
2253             }
2254             while(st->in_directory.endsWith(Option::dir_sep))
2255                 st->in_directory.chop(1);
2256             if(fileInfo(st->in_directory).isRelative())
2257                 st->out_directory = st->in_directory;
2258             else
2259                 st->out_directory = fileFixify(st->in_directory, qmake_getpwd(), Option::output_dir);
2260             if(!project->isEmpty(fixedSubdir + ".makefile")) {
2261                 st->makefile = project->first(fixedSubdir + ".makefile");
2262             } else {
2263                 st->makefile = "Makefile";
2264                 if(!st->profile.isEmpty()) {
2265                     QString basename = st->in_directory;
2266                     int new_slsh = basename.lastIndexOf(Option::dir_sep);
2267                     if(new_slsh != -1)
2268                         basename = basename.mid(new_slsh+1);
2269                     if(st->profile != basename + Option::pro_ext)
2270                         st->makefile += "." + st->profile.left(st->profile.length() - Option::pro_ext.length());
2271                 }
2272             }
2273             if(!project->isEmpty(fixedSubdir + ".depends")) {
2274                 const QStringList depends = project->values(fixedSubdir + ".depends");
2275                 for(int depend = 0; depend < depends.size(); ++depend) {
2276                     bool found = false;
2277                     for(int subDep = 0; subDep < subdirs.size(); ++subDep) {
2278                         if(subdirs[subDep] == depends.at(depend)) {
2279                             QString fixedSubDep = subdirs[subDep];
2280                             fixedSubDep = fixedSubDep.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2281                             if(!project->isEmpty(fixedSubDep + ".target")) {
2282                                 st->depends += project->first(fixedSubDep + ".target");
2283                             } else {
2284                                 QString d = Option::fixPathToLocalOS(subdirs[subDep]);
2285                                 if(!project->isEmpty(fixedSubDep + ".file"))
2286                                     d = project->first(fixedSubDep + ".file");
2287                                 else if(!project->isEmpty(fixedSubDep + ".subdir"))
2288                                     d = project->first(fixedSubDep + ".subdir");
2289                                 st->depends += "sub-" + d.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2290                             }
2291                             found = true;
2292                             break;
2293                         }
2294                     }
2295                     if(!found) {
2296                         QString depend_str = depends.at(depend);
2297                         st->depends += depend_str.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2298                     }
2299                 }
2300             }
2301             if(!project->isEmpty(fixedSubdir + ".target")) {
2302                 st->target = project->first(fixedSubdir + ".target");
2303             } else {
2304                 st->target = "sub-" + file;
2305         st->target = st->target.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2306             }
2307         }
2308     }
2309     return targets;
2310 }
2311
2312 void
2313 MakefileGenerator::writeSubDirs(QTextStream &t)
2314 {
2315     QList<SubTarget*> targets = findSubDirsSubTargets();
2316     t << "first: make_first" << endl;
2317     int flags = SubTargetInstalls;
2318     if(project->isActiveConfig("ordered"))
2319         flags |= SubTargetOrdered;
2320     writeSubTargets(t, targets, flags);
2321     qDeleteAll(targets);
2322 }
2323
2324 void MakefileGenerator::writeSubMakeCall(QTextStream &t, const QString &callPrefix,
2325                                          const QString &makeArguments)
2326 {
2327     t << callPrefix << "$(MAKE)" << makeArguments << endl;
2328 }
2329
2330 void
2331 MakefileGenerator::writeSubTargetCall(QTextStream &t,
2332         const QString &in_directory, const QString &in, const QString &out_directory, const QString &out,
2333         const QString &out_directory_cdin, const QString &makefilein)
2334 {
2335     QString pfx;
2336     if (!in.isEmpty()) {
2337         if (!in_directory.isEmpty())
2338             t << "\n\t" << mkdir_p_asstring(out_directory);
2339         pfx = "( " + chkfile + " " + out + " " + chkglue
2340               + "$(QMAKE) " + in + buildArgs(in_directory) + " -o " + out
2341               + " ) && ";
2342     }
2343     writeSubMakeCall(t, out_directory_cdin + pfx, makefilein);
2344 }
2345
2346 void
2347 MakefileGenerator::writeSubTargets(QTextStream &t, QList<MakefileGenerator::SubTarget*> targets, int flags)
2348 {
2349     // blasted includes
2350     const QStringList &qeui = project->values("QMAKE_EXTRA_INCLUDES");
2351     for (QStringList::ConstIterator qeui_it = qeui.begin(); qeui_it != qeui.end(); ++qeui_it)
2352         t << "include " << (*qeui_it) << endl;
2353
2354     if (!(flags & SubTargetSkipDefaultVariables)) {
2355         QString ofile = Option::fixPathToTargetOS(Option::output.fileName());
2356         if(ofile.lastIndexOf(Option::dir_sep) != -1)
2357             ofile.remove(0, ofile.lastIndexOf(Option::dir_sep) +1);
2358         t << "MAKEFILE      = " << ofile << endl;
2359         /* Calling Option::fixPathToTargetOS() is necessary for MinGW/MSYS, which requires
2360          * back-slashes to be turned into slashes. */
2361         t << "QMAKE         = " << var("QMAKE_QMAKE") << endl;
2362         t << "DEL_FILE      = " << var("QMAKE_DEL_FILE") << endl;
2363         t << "CHK_DIR_EXISTS= " << var("QMAKE_CHK_DIR_EXISTS") << endl;
2364         t << "MKDIR         = " << var("QMAKE_MKDIR") << endl;
2365         t << "COPY          = " << var("QMAKE_COPY") << endl;
2366         t << "COPY_FILE     = " << var("QMAKE_COPY_FILE") << endl;
2367         t << "COPY_DIR      = " << var("QMAKE_COPY_DIR") << endl;
2368         t << "INSTALL_FILE  = " << var("QMAKE_INSTALL_FILE") << endl;
2369         t << "INSTALL_PROGRAM = " << var("QMAKE_INSTALL_PROGRAM") << endl;
2370         t << "INSTALL_DIR   = " << var("QMAKE_INSTALL_DIR") << endl;
2371         t << "DEL_FILE      = " << var("QMAKE_DEL_FILE") << endl;
2372         t << "SYMLINK       = " << var("QMAKE_SYMBOLIC_LINK") << endl;
2373         t << "DEL_DIR       = " << var("QMAKE_DEL_DIR") << endl;
2374         t << "MOVE          = " << var("QMAKE_MOVE") << endl;
2375         t << "SUBTARGETS    = ";     // subtargets are sub-directory
2376         for(int target = 0; target < targets.size(); ++target)
2377             t << " \\\n\t\t" << targets.at(target)->target;
2378         t << endl << endl;
2379     }
2380     writeExtraVariables(t);
2381
2382     QStringList targetSuffixes;
2383     const QString abs_source_path = project->first("QMAKE_ABSOLUTE_SOURCE_PATH");
2384     if (!(flags & SubTargetSkipDefaultTargets)) {
2385         targetSuffixes << "make_first" << "all" << "clean" << "distclean"
2386                        << QString((flags & SubTargetInstalls) ? "install_subtargets" : "install")
2387                        << QString((flags & SubTargetInstalls) ? "uninstall_subtargets" : "uninstall");
2388     }
2389
2390     bool dont_recurse = project->isActiveConfig("dont_recurse");
2391
2392     // generate target rules
2393     for(int target = 0; target < targets.size(); ++target) {
2394         SubTarget *subtarget = targets.at(target);
2395         QString in_directory = subtarget->in_directory;
2396         if(!in_directory.isEmpty() && !in_directory.endsWith(Option::dir_sep))
2397             in_directory += Option::dir_sep;
2398         QString out_directory = subtarget->out_directory;
2399         if(!out_directory.isEmpty() && !out_directory.endsWith(Option::dir_sep))
2400             out_directory += Option::dir_sep;
2401         if(!abs_source_path.isEmpty() && out_directory.startsWith(abs_source_path))
2402             out_directory = Option::output_dir + out_directory.mid(abs_source_path.length());
2403
2404         QString out_directory_cdin = out_directory.isEmpty() ? "\n\t"
2405                                                              : "\n\tcd " + out_directory + " && ";
2406         QString makefilein = " -f " + subtarget->makefile;
2407
2408         //qmake it
2409         QString out;
2410         QString in;
2411         if(!subtarget->profile.isEmpty()) {
2412             out = subtarget->makefile;
2413             in = escapeFilePath(fileFixify(in_directory + subtarget->profile, FileFixifyAbsolute));
2414             if(out.startsWith(in_directory))
2415                 out = out.mid(in_directory.length());
2416             t << subtarget->target << "-qmake_all: ";
2417             if (flags & SubTargetOrdered) {
2418                 if (target)
2419                     t << targets.at(target - 1)->target << "-qmake_all";
2420             } else {
2421                 if (!subtarget->depends.isEmpty())
2422                     t << valGlue(subtarget->depends, QString(), "-qmake_all ", "-qmake_all");
2423             }
2424             t << " FORCE\n\t";
2425             if(!in_directory.isEmpty()) {
2426                 t << mkdir_p_asstring(out_directory)
2427                   << out_directory_cdin;
2428             }
2429             t << "$(QMAKE) " << in << buildArgs(in_directory) << " -o " << out;
2430             if (!dont_recurse)
2431                 writeSubMakeCall(t, out_directory_cdin, makefilein + " qmake_all");
2432             else
2433                 t << endl;
2434         }
2435
2436         { //actually compile
2437             t << subtarget->target << ":";
2438             if(!subtarget->depends.isEmpty())
2439                 t << " " << valList(subtarget->depends);
2440             t << " FORCE";
2441             writeSubTargetCall(t, in_directory, in, out_directory, out,
2442                                out_directory_cdin, makefilein);
2443         }
2444
2445         for(int suffix = 0; suffix < targetSuffixes.size(); ++suffix) {
2446             QString s = targetSuffixes.at(suffix);
2447             if(s == "install_subtargets")
2448                 s = "install";
2449             else if(s == "uninstall_subtargets")
2450                 s = "uninstall";
2451             else if(s == "make_first")
2452                 s = QString();
2453
2454             if(flags & SubTargetOrdered) {
2455                 t << subtarget->target << "-" << targetSuffixes.at(suffix) << "-ordered:";
2456                 if(target)
2457                     t << " " << targets.at(target-1)->target << "-" << targetSuffixes.at(suffix) << "-ordered ";
2458                 t << " FORCE";
2459                 writeSubTargetCall(t, in_directory, in, out_directory, out,
2460                                    out_directory_cdin, makefilein + " " + s);
2461             }
2462             t << subtarget->target << "-" << targetSuffixes.at(suffix) << ":";
2463             if(!subtarget->depends.isEmpty())
2464                 t << " " << valGlue(subtarget->depends, QString(), "-" + targetSuffixes.at(suffix) + " ",
2465                                     "-"+targetSuffixes.at(suffix));
2466             t << " FORCE";
2467             writeSubTargetCall(t, in_directory, in, out_directory, out,
2468                                out_directory_cdin, makefilein + " " + s);
2469         }
2470     }
2471     t << endl;
2472
2473     if (!(flags & SubTargetSkipDefaultTargets)) {
2474         writeMakeQmake(t, true);
2475
2476         t << "qmake_all:";
2477         if(!targets.isEmpty()) {
2478             for(QList<SubTarget*>::Iterator it = targets.begin(); it != targets.end(); ++it) {
2479                 if(!(*it)->profile.isEmpty())
2480                     t << " " << (*it)->target << "-" << "qmake_all";
2481             }
2482         }
2483         t << " FORCE" << endl << endl;
2484     }
2485
2486     for(int s = 0; s < targetSuffixes.size(); ++s) {
2487         QString suffix = targetSuffixes.at(s);
2488         if(!(flags & SubTargetInstalls) && suffix.endsWith("install"))
2489             continue;
2490
2491         t << suffix << ":";
2492         for(int target = 0; target < targets.size(); ++target) {
2493             SubTarget *subTarget = targets.at(target);
2494             if (suffix == "make_first"
2495                 && project->values(subTarget->name + ".CONFIG").indexOf("no_default_target") != -1) {
2496                 continue;
2497             }
2498             if((suffix == "install_subtargets" || suffix == "uninstall_subtargets")
2499                 && project->values(subTarget->name + ".CONFIG").indexOf("no_default_install") != -1) {
2500                 continue;
2501             }
2502             QString targetRule = subTarget->target + "-" + suffix;
2503             if(flags & SubTargetOrdered)
2504                 targetRule += "-ordered";
2505             t << " " << targetRule;
2506         }
2507         if(suffix == "all" || suffix == "make_first")
2508             t << varGlue("ALL_DEPS"," "," ","");
2509         if(suffix == "clean")
2510             t << varGlue("CLEAN_DEPS"," "," ","");
2511         t << " FORCE" << endl;
2512         if(suffix == "clean") {
2513             t << fileVarGlue("QMAKE_CLEAN", "\t-$(DEL_FILE) ", "\n\t-$(DEL_FILE) ", "\n");
2514         } else if(suffix == "distclean") {
2515             QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
2516             if(!ofile.isEmpty())
2517                 t << "\t-$(DEL_FILE) " << ofile << endl;
2518             t << fileVarGlue("QMAKE_DISTCLEAN", "\t-$(DEL_FILE) ", " ", "\n");
2519         }
2520     }
2521
2522     // user defined targets
2523     const QStringList &qut = project->values("QMAKE_EXTRA_TARGETS");
2524     for (QStringList::ConstIterator qut_it = qut.begin(); qut_it != qut.end(); ++qut_it) {
2525         QString targ = var((*qut_it) + ".target"),
2526                  cmd = var((*qut_it) + ".commands"), deps;
2527         if(targ.isEmpty())
2528             targ = (*qut_it);
2529         t << endl;
2530
2531         const QStringList &deplist = project->values((*qut_it) + ".depends");
2532         for (QStringList::ConstIterator dep_it = deplist.begin(); dep_it != deplist.end(); ++dep_it) {
2533             QString dep = var((*dep_it) + ".target");
2534             if(dep.isEmpty())
2535                 dep = Option::fixPathToTargetOS(*dep_it, false);
2536             deps += " " + dep;
2537         }
2538         if(project->values((*qut_it) + ".CONFIG").indexOf("recursive") != -1) {
2539             QSet<QString> recurse;
2540             if(project->isSet((*qut_it) + ".recurse")) {
2541                 recurse = project->values((*qut_it) + ".recurse").toSet();
2542             } else {
2543                 for(int target = 0; target < targets.size(); ++target)
2544                     recurse.insert(targets.at(target)->name);
2545             }
2546             for(int target = 0; target < targets.size(); ++target) {
2547                 SubTarget *subtarget = targets.at(target);
2548                 QString in_directory = subtarget->in_directory;
2549                 if(!in_directory.isEmpty() && !in_directory.endsWith(Option::dir_sep))
2550                     in_directory += Option::dir_sep;
2551                 QString out_directory = subtarget->out_directory;
2552                 if(!out_directory.isEmpty() && !out_directory.endsWith(Option::dir_sep))
2553                     out_directory += Option::dir_sep;
2554                 if(!abs_source_path.isEmpty() && out_directory.startsWith(abs_source_path))
2555                     out_directory = Option::output_dir + out_directory.mid(abs_source_path.length());
2556
2557                 if(!recurse.contains(subtarget->name))
2558                     continue;
2559
2560                 QString out_directory_cdin = out_directory.isEmpty() ? "\n\t"
2561                                                                      : "\n\tcd " + out_directory + " && ";
2562                 QString makefilein = " -f " + subtarget->makefile;
2563
2564                 QString out;
2565                 QString in;
2566                 if (!subtarget->profile.isEmpty()) {
2567                     out = subtarget->makefile;
2568                     in = escapeFilePath(fileFixify(in_directory + subtarget->profile, FileFixifyAbsolute));
2569                     if (out.startsWith(in_directory))
2570                         out = out.mid(in_directory.length());
2571                 }
2572
2573                 //write the rule/depends
2574                 if(flags & SubTargetOrdered) {
2575                     const QString dep = subtarget->target + "-" + (*qut_it) + "_ordered";
2576                     t << dep << ":";
2577                     if(target)
2578                         t << " " << targets.at(target-1)->target << "-" << (*qut_it) << "_ordered ";
2579                     deps += " " + dep;
2580                 } else {
2581                     const QString dep = subtarget->target + "-" + (*qut_it);
2582                     t << dep << ":";
2583                     if(!subtarget->depends.isEmpty())
2584                         t << " " << valGlue(subtarget->depends, QString(), "-" + (*qut_it) + " ", "-" + (*qut_it));
2585                     deps += " " + dep;
2586                 }
2587
2588                 QString sub_targ = targ;
2589                 if(project->isSet((*qut_it) + ".recurse_target"))
2590                     sub_targ = project->first((*qut_it) + ".recurse_target");
2591
2592                 //write the commands
2593                 writeSubTargetCall(t, in_directory, in, out_directory, out,
2594                                    out_directory_cdin, makefilein + " " + sub_targ);
2595             }
2596         }
2597         if (project->values((*qut_it) + ".CONFIG").indexOf("phony") != -1)
2598             deps += " FORCE";
2599         t << targ << ":" << deps << "\n";
2600         if(!cmd.isEmpty())
2601             t << "\t" << cmd << endl;
2602     }
2603
2604     if(flags & SubTargetInstalls) {
2605         project->values("INSTALLDEPS")   += "install_subtargets";
2606         project->values("UNINSTALLDEPS") += "uninstall_subtargets";
2607         writeInstalls(t, "INSTALLS", true);
2608     }
2609     t << "FORCE:" << endl << endl;
2610 }
2611
2612 void
2613 MakefileGenerator::writeMakeQmake(QTextStream &t, bool noDummyQmakeAll)
2614 {
2615     QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
2616     if(project->isEmpty("QMAKE_FAILED_REQUIREMENTS") && !project->isEmpty("QMAKE_INTERNAL_PRL_FILE")) {
2617         QStringList files = fileFixify(Option::mkfile::project_files);
2618         t << escapeDependencyPath(project->first("QMAKE_INTERNAL_PRL_FILE")) << ": " << "\n\t"
2619           << "@$(QMAKE) -prl " << buildArgs() << " " << files.join(" ") << endl;
2620     }
2621
2622     QString pfile = project->projectFile();
2623     if(pfile != "(stdin)") {
2624         QString qmake = build_args();
2625         if(!ofile.isEmpty() && !project->isActiveConfig("no_autoqmake")) {
2626             t << escapeFilePath(ofile) << ": " << escapeDependencyPath(fileFixify(pfile)) << " ";
2627             if (Option::mkfile::do_cache) {
2628                 if (!project->confFile().isEmpty())
2629                     t <<  escapeDependencyPath(fileFixify(project->confFile())) << " ";
2630                 if (!project->cacheFile().isEmpty())
2631                     t <<  escapeDependencyPath(fileFixify(project->cacheFile())) << " ";
2632             }
2633             if(!specdir().isEmpty()) {
2634                 if(exists(Option::fixPathToLocalOS(specdir()+QDir::separator()+"qmake.conf")))
2635                     t << escapeDependencyPath(specdir() + Option::dir_sep + "qmake.conf") << " ";
2636             }
2637             const QStringList &included = project->values("QMAKE_INTERNAL_INCLUDED_FILES");
2638             t << escapeDependencyPaths(included).join(" \\\n\t\t") << "\n\t"
2639               << qmake << endl;
2640             for(int include = 0; include < included.size(); ++include) {
2641                 const QString i(included.at(include));
2642                 if(!i.isEmpty())
2643                     t << i << ":" << endl;
2644             }
2645         }
2646         if(project->first("QMAKE_ORIG_TARGET") != "qmake") {
2647             t << "qmake: FORCE\n\t@" << qmake << endl << endl;
2648             if (!noDummyQmakeAll)
2649                 t << "qmake_all: FORCE" << endl << endl;
2650         }
2651     }
2652 }
2653
2654 QFileInfo
2655 MakefileGenerator::fileInfo(QString file) const
2656 {
2657     static QHash<FileInfoCacheKey, QFileInfo> *cache = 0;
2658     static QFileInfo noInfo = QFileInfo();
2659     if(!cache) {
2660         cache = new QHash<FileInfoCacheKey, QFileInfo>;
2661         qmakeAddCacheClear(qmakeDeleteCacheClear<QHash<FileInfoCacheKey, QFileInfo> >, (void**)&cache);
2662     }
2663     FileInfoCacheKey cacheKey(file);
2664     QFileInfo value = cache->value(cacheKey, noInfo);
2665     if (value != noInfo)
2666         return value;
2667
2668     QFileInfo fi(file);
2669     if (fi.exists())
2670         cache->insert(cacheKey, fi);
2671     return fi;
2672 }
2673
2674 QString
2675 MakefileGenerator::unescapeFilePath(const QString &path) const
2676 {
2677     QString ret = path;
2678     if(!ret.isEmpty()) {
2679         if(ret.contains(QLatin1String("\\ ")))
2680             ret.replace(QLatin1String("\\ "), QLatin1String(" "));
2681         if(ret.contains(QLatin1Char('\"')))
2682             ret.remove(QLatin1Char('\"'));
2683     }
2684     return ret;
2685 }
2686
2687 QStringList
2688 MakefileGenerator::escapeFilePaths(const QStringList &paths) const
2689 {
2690     QStringList ret;
2691     for(int i = 0; i < paths.size(); ++i)
2692         ret.append(escapeFilePath(paths.at(i)));
2693     return ret;
2694 }
2695
2696 QStringList
2697 MakefileGenerator::escapeDependencyPaths(const QStringList &paths) const
2698 {
2699     QStringList ret;
2700     for(int i = 0; i < paths.size(); ++i)
2701         ret.append(escapeDependencyPath(paths.at(i)));
2702     return ret;
2703 }
2704
2705 QStringList
2706 MakefileGenerator::unescapeFilePaths(const QStringList &paths) const
2707 {
2708     QStringList ret;
2709     for(int i = 0; i < paths.size(); ++i)
2710         ret.append(unescapeFilePath(paths.at(i)));
2711     return ret;
2712 }
2713
2714 QStringList
2715 MakefileGenerator::fileFixify(const QStringList& files, const QString &out_dir, const QString &in_dir,
2716                               FileFixifyType fix, bool canon) const
2717 {
2718     if(files.isEmpty())
2719         return files;
2720     QStringList ret;
2721     for(QStringList::ConstIterator it = files.begin(); it != files.end(); ++it) {
2722         if(!(*it).isEmpty())
2723             ret << fileFixify((*it), out_dir, in_dir, fix, canon);
2724     }
2725     return ret;
2726 }
2727
2728 QString
2729 MakefileGenerator::fileFixify(const QString& file, const QString &out_d, const QString &in_d,
2730                               FileFixifyType fix, bool canon) const
2731 {
2732     if(file.isEmpty())
2733         return file;
2734     QString ret = unescapeFilePath(file);
2735
2736     //do the fixin'
2737     QString orig_file = ret;
2738     if(ret.startsWith(QLatin1Char('~'))) {
2739         if(ret.startsWith(QLatin1String("~/")))
2740             ret = QDir::homePath() + ret.mid(1);
2741         else
2742             warn_msg(WarnLogic, "Unable to expand ~ in %s", ret.toLatin1().constData());
2743     }
2744     if(fix == FileFixifyAbsolute || (fix == FileFixifyDefault && project->isActiveConfig("no_fixpath"))) {
2745         if(fix == FileFixifyAbsolute && QDir::isRelativePath(ret)) { //already absolute
2746             QString pwd = qmake_getpwd();
2747             if (!pwd.endsWith(QLatin1Char('/')))
2748                 pwd += QLatin1Char('/');
2749             ret.prepend(pwd);
2750         }
2751         ret = Option::fixPathToTargetOS(ret, false, canon);
2752     } else { //fix it..
2753         QString out_dir = QDir(Option::output_dir).absoluteFilePath(out_d);
2754         QString in_dir  = QDir(qmake_getpwd()).absoluteFilePath(in_d);
2755         {
2756             QFileInfo in_fi(fileInfo(in_dir));
2757             if(in_fi.exists())
2758                 in_dir = in_fi.canonicalFilePath();
2759             QFileInfo out_fi(fileInfo(out_dir));
2760             if(out_fi.exists())
2761                 out_dir = out_fi.canonicalFilePath();
2762         }
2763
2764         QString qfile(Option::fixPathToLocalOS(ret, true, canon));
2765         QFileInfo qfileinfo(fileInfo(qfile));
2766         if(out_dir != in_dir || !qfileinfo.isRelative()) {
2767             if(qfileinfo.isRelative()) {
2768                 ret = in_dir + "/" + qfile;
2769                 qfileinfo.setFile(ret);
2770             }
2771             ret = Option::fixPathToTargetOS(ret, false, canon);
2772             if(canon && qfileinfo.exists() &&
2773                file == Option::fixPathToTargetOS(ret, true, canon))
2774                 ret = Option::fixPathToTargetOS(qfileinfo.canonicalFilePath());
2775             QString match_dir = Option::fixPathToTargetOS(out_dir, false, canon);
2776             if(ret == match_dir) {
2777                 ret = "";
2778             } else if(ret.startsWith(match_dir + Option::dir_sep)) {
2779                 ret = ret.mid(match_dir.length() + Option::dir_sep.length());
2780             } else {
2781                 //figure out the depth
2782                 int depth = 4;
2783                 if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE ||
2784                    Option::qmake_mode == Option::QMAKE_GENERATE_PRL) {
2785                     if(project && !project->isEmpty("QMAKE_PROJECT_DEPTH"))
2786                         depth = project->first("QMAKE_PROJECT_DEPTH").toInt();
2787                     else if(Option::mkfile::cachefile_depth != -1)
2788                         depth = Option::mkfile::cachefile_depth;
2789                 }
2790                 //calculate how much can be removed
2791                 QString dot_prefix;
2792                 for(int i = 1; i <= depth; i++) {
2793                     int sl = match_dir.lastIndexOf(Option::dir_sep);
2794                     if(sl == -1)
2795                         break;
2796                     match_dir = match_dir.left(sl);
2797                     if(match_dir.isEmpty())
2798                         break;
2799                     if(ret.startsWith(match_dir + Option::dir_sep)) {
2800                         //concat
2801                         int remlen = ret.length() - (match_dir.length() + 1);
2802                         if(remlen < 0)
2803                             remlen = 0;
2804                         ret = ret.right(remlen);
2805                         //prepend
2806                         for(int o = 0; o < i; o++)
2807                             dot_prefix += ".." + Option::dir_sep;
2808                         break;
2809                     }
2810                 }
2811                 ret.prepend(dot_prefix);
2812             }
2813         } else {
2814             ret = Option::fixPathToTargetOS(ret, false, canon);
2815         }
2816     }
2817     if(ret.isEmpty())
2818         ret = ".";
2819     debug_msg(3, "Fixed[%d,%d] %s :: to :: %s [%s::%s] [%s::%s]", fix, canon, orig_file.toLatin1().constData(),
2820               ret.toLatin1().constData(), in_d.toLatin1().constData(), out_d.toLatin1().constData(),
2821               qmake_getpwd().toLatin1().constData(), Option::output_dir.toLatin1().constData());
2822     return ret;
2823 }
2824
2825 void
2826 MakefileGenerator::checkMultipleDefinition(const QString &f, const QString &w)
2827 {
2828     if(!(Option::warn_level & WarnLogic))
2829         return;
2830     QString file = f;
2831     int slsh = f.lastIndexOf(Option::dir_sep);
2832     if(slsh != -1)
2833         file.remove(0, slsh + 1);
2834     const QStringList &l = project->values(w);
2835     for (QStringList::ConstIterator val_it = l.begin(); val_it != l.end(); ++val_it) {
2836         QString file2((*val_it));
2837         slsh = file2.lastIndexOf(Option::dir_sep);
2838         if(slsh != -1)
2839             file2.remove(0, slsh + 1);
2840         if(file2 == file) {
2841             warn_msg(WarnLogic, "Found potential symbol conflict of %s (%s) in %s",
2842                      file.toLatin1().constData(), (*val_it).toLatin1().constData(), w.toLatin1().constData());
2843             break;
2844         }
2845     }
2846 }
2847
2848 QMakeLocalFileName
2849 MakefileGenerator::fixPathForFile(const QMakeLocalFileName &file, bool forOpen)
2850 {
2851     if(forOpen)
2852         return QMakeLocalFileName(fileFixify(file.real(), qmake_getpwd(), Option::output_dir));
2853     return QMakeLocalFileName(fileFixify(file.real()));
2854 }
2855
2856 QFileInfo
2857 MakefileGenerator::findFileInfo(const QMakeLocalFileName &file)
2858 {
2859     return fileInfo(file.local());
2860 }
2861
2862 QMakeLocalFileName
2863 MakefileGenerator::findFileForDep(const QMakeLocalFileName &dep, const QMakeLocalFileName &file)
2864 {
2865     QMakeLocalFileName ret;
2866     if(!project->isEmpty("SKIP_DEPENDS")) {
2867         bool found = false;
2868         const QStringList &nodeplist = project->values("SKIP_DEPENDS");
2869         for (QStringList::ConstIterator it = nodeplist.begin();
2870             it != nodeplist.end(); ++it) {
2871             QRegExp regx((*it));
2872             if(regx.indexIn(dep.local()) != -1) {
2873                 found = true;
2874                 break;
2875             }
2876         }
2877         if(found)
2878             return ret;
2879     }
2880
2881     ret = QMakeSourceFileInfo::findFileForDep(dep, file);
2882     if(!ret.isNull())
2883         return ret;
2884
2885     //these are some "hacky" heuristics it will try to do on an include
2886     //however these can be turned off at runtime, I'm not sure how
2887     //reliable these will be, most likely when problems arise turn it off
2888     //and see if they go away..
2889     if(Option::mkfile::do_dep_heuristics) {
2890         if(depHeuristicsCache.contains(dep.real()))
2891             return depHeuristicsCache[dep.real()];
2892
2893         if(Option::output_dir != qmake_getpwd()
2894            && QDir::isRelativePath(dep.real())) { //is it from the shadow tree
2895             QList<QMakeLocalFileName> depdirs = QMakeSourceFileInfo::dependencyPaths();
2896             depdirs.prepend(fileInfo(file.real()).absoluteDir().path());
2897             QString pwd = qmake_getpwd();
2898             if(pwd.at(pwd.length()-1) != '/')
2899                 pwd += '/';
2900             for(int i = 0; i < depdirs.count(); i++) {
2901                 QString dir = depdirs.at(i).real();
2902                 if(!QDir::isRelativePath(dir) && dir.startsWith(pwd))
2903                     dir = dir.mid(pwd.length());
2904                 if(QDir::isRelativePath(dir)) {
2905                     if(!dir.endsWith(Option::dir_sep))
2906                         dir += Option::dir_sep;
2907                     QString shadow = fileFixify(dir + dep.local(), pwd, Option::output_dir);
2908                     if(exists(shadow)) {
2909                         ret = QMakeLocalFileName(shadow);
2910                         goto found_dep_from_heuristic;
2911                     }
2912                 }
2913             }
2914         }
2915         { //is it from an EXTRA_TARGET
2916             const QString dep_basename = dep.local().section(Option::dir_sep, -1);
2917             const QStringList &qut = project->values("QMAKE_EXTRA_TARGETS");
2918             for (QStringList::ConstIterator it = qut.begin(); it != qut.end(); ++it) {
2919                 QString targ = var((*it) + ".target");
2920                 if(targ.isEmpty())
2921                     targ = (*it);
2922                 QString out = Option::fixPathToTargetOS(targ);
2923                 if(out == dep.real() || out.section(Option::dir_sep, -1) == dep_basename) {
2924                     ret = QMakeLocalFileName(out);
2925                     goto found_dep_from_heuristic;
2926                 }
2927             }
2928         }
2929         { //is it from an EXTRA_COMPILER
2930             const QString dep_basename = dep.local().section(Option::dir_sep, -1);
2931             const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
2932             for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
2933                 QString tmp_out = project->values((*it) + ".output").first();
2934                 if(tmp_out.isEmpty())
2935                     continue;
2936                 const QStringList &tmp = project->values((*it) + ".input");
2937                 for (QStringList::ConstIterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) {
2938                     const QStringList &inputs = project->values((*it2));
2939                     for (QStringList::ConstIterator input = inputs.begin(); input != inputs.end(); ++input) {
2940                         QString out = Option::fixPathToTargetOS(unescapeFilePath(replaceExtraCompilerVariables(tmp_out, (*input), QString())));
2941               if(out == dep.real() || out.section(Option::dir_sep, -1) == dep_basename) {
2942                             ret = QMakeLocalFileName(fileFixify(out, qmake_getpwd(), Option::output_dir));
2943                             goto found_dep_from_heuristic;
2944                         }
2945                     }
2946                 }
2947             }
2948         }
2949     found_dep_from_heuristic:
2950         depHeuristicsCache.insert(dep.real(), ret);
2951     }
2952     return ret;
2953 }
2954
2955 QStringList
2956 &MakefileGenerator::findDependencies(const QString &file)
2957 {
2958     const QString fixedFile = fileFixify(file);
2959     if(!dependsCache.contains(fixedFile)) {
2960 #if 1
2961         QStringList deps = QMakeSourceFileInfo::dependencies(file);
2962         if(file != fixedFile)
2963             deps += QMakeSourceFileInfo::dependencies(fixedFile);
2964 #else
2965         QStringList deps = QMakeSourceFileInfo::dependencies(fixedFile);
2966 #endif
2967         dependsCache.insert(fixedFile, deps);
2968     }
2969     return dependsCache[fixedFile];
2970 }
2971
2972 QString
2973 MakefileGenerator::specdir()
2974 {
2975     if (spec.isEmpty())
2976         spec = fileFixify(project->specDir());
2977     return spec;
2978 }
2979
2980 bool
2981 MakefileGenerator::openOutput(QFile &file, const QString &build) const
2982 {
2983     {
2984         QString outdir;
2985         if(!file.fileName().isEmpty()) {
2986             if(QDir::isRelativePath(file.fileName()))
2987                 file.setFileName(Option::output_dir + "/" + file.fileName()); //pwd when qmake was run
2988             QFileInfo fi(fileInfo(file.fileName()));
2989             if(fi.isDir())
2990                 outdir = file.fileName() + '/';
2991         }
2992         if(!outdir.isEmpty() || file.fileName().isEmpty()) {
2993             QString fname = "Makefile";
2994             if(!project->isEmpty("MAKEFILE"))
2995                fname = project->first("MAKEFILE");
2996             file.setFileName(outdir + fname);
2997         }
2998     }
2999     if(QDir::isRelativePath(file.fileName())) {
3000         QString fname = Option::output_dir;  //pwd when qmake was run
3001         if(!fname.endsWith("/"))
3002             fname += "/";
3003         fname += file.fileName();
3004         file.setFileName(fname);
3005     }
3006     if(!build.isEmpty())
3007         file.setFileName(file.fileName() + "." + build);
3008     if(project->isEmpty("QMAKE_MAKEFILE"))
3009         project->values("QMAKE_MAKEFILE").append(file.fileName());
3010     int slsh = file.fileName().lastIndexOf('/');
3011     if(slsh != -1)
3012         mkdir(file.fileName().left(slsh));
3013     if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
3014         QFileInfo fi(fileInfo(Option::output.fileName()));
3015         QString od;
3016         if(fi.isSymLink())
3017             od = fileInfo(fi.readLink()).absolutePath();
3018         else
3019             od = fi.path();
3020         od = QDir::fromNativeSeparators(od);
3021         if(QDir::isRelativePath(od)) {
3022             QString dir = Option::output_dir;
3023             if (!dir.endsWith('/') && !od.isEmpty())
3024                 dir += '/';
3025             od.prepend(dir);
3026         }
3027         Option::output_dir = od;
3028         return true;
3029     }
3030     return false;
3031 }
3032
3033 QString
3034 MakefileGenerator::pkgConfigFileName(bool fixify)
3035 {
3036     QString ret = var("TARGET");
3037     int slsh = ret.lastIndexOf(Option::dir_sep);
3038     if(slsh != -1)
3039         ret = ret.right(ret.length() - slsh - 1);
3040     if(ret.startsWith("lib"))
3041         ret = ret.mid(3);
3042     int dot = ret.indexOf('.');
3043     if(dot != -1)
3044         ret = ret.left(dot);
3045     ret += Option::pkgcfg_ext;
3046     QString subdir = project->first("QMAKE_PKGCONFIG_DESTDIR");
3047     if(!subdir.isEmpty()) {
3048         // initOutPaths() appends dir_sep, but just to be safe..
3049         if (!subdir.endsWith(Option::dir_sep))
3050             ret.prepend(Option::dir_sep);
3051         ret.prepend(subdir);
3052     }
3053     if(fixify) {
3054         if(QDir::isRelativePath(ret) && !project->isEmpty("DESTDIR"))
3055             ret.prepend(project->first("DESTDIR"));
3056         ret = Option::fixPathToLocalOS(fileFixify(ret, qmake_getpwd(), Option::output_dir));
3057     }
3058     return ret;
3059 }
3060
3061 QString
3062 MakefileGenerator::pkgConfigPrefix() const
3063 {
3064     if(!project->isEmpty("QMAKE_PKGCONFIG_PREFIX"))
3065         return project->first("QMAKE_PKGCONFIG_PREFIX");
3066     return QLibraryInfo::rawLocation(QLibraryInfo::PrefixPath, QLibraryInfo::FinalPaths);
3067 }
3068
3069 QString
3070 MakefileGenerator::pkgConfigFixPath(QString path) const
3071 {
3072     QString prefix = pkgConfigPrefix();
3073     if(path.startsWith(prefix))
3074         path = path.replace(prefix, "${prefix}");
3075     return path;
3076 }
3077
3078 void
3079 MakefileGenerator::writePkgConfigFile()
3080 {
3081     QString fname = pkgConfigFileName(), lname = fname;
3082     mkdir(fileInfo(fname).path());
3083     int slsh = lname.lastIndexOf(Option::dir_sep);
3084     if(slsh != -1)
3085         lname = lname.right(lname.length() - slsh - 1);
3086     QFile ft(fname);
3087     if(!ft.open(QIODevice::WriteOnly))
3088         return;
3089     project->values("ALL_DEPS").append(fileFixify(fname));
3090     QTextStream t(&ft);
3091
3092     QString prefix = pkgConfigPrefix();
3093     QString libDir = project->first("QMAKE_PKGCONFIG_LIBDIR");
3094     if(libDir.isEmpty())
3095         libDir = prefix + Option::dir_sep + "lib" + Option::dir_sep;
3096     QString includeDir = project->first("QMAKE_PKGCONFIG_INCDIR");
3097     if(includeDir.isEmpty())
3098         includeDir = prefix + "/include";
3099
3100     t << "prefix=" << prefix << endl;
3101     t << "exec_prefix=${prefix}\n"
3102       << "libdir=" << pkgConfigFixPath(libDir) << "\n"
3103       << "includedir=" << pkgConfigFixPath(includeDir) << endl;
3104     t << endl;
3105
3106     //extra PKGCONFIG variables
3107     const QStringList &pkgconfig_vars = project->values("QMAKE_PKGCONFIG_VARIABLES");
3108     for(int i = 0; i < pkgconfig_vars.size(); ++i) {
3109         QString var = project->first(pkgconfig_vars.at(i) + ".name"),
3110                 val = project->values(pkgconfig_vars.at(i) + ".value").join(" ");
3111         if(var.isEmpty())
3112             continue;
3113         if(val.isEmpty()) {
3114             const QStringList &var_vars = project->values(pkgconfig_vars.at(i) + ".variable");
3115             for(int v = 0; v < var_vars.size(); ++v) {
3116                 const QStringList &vars = project->values(var_vars.at(v));
3117                 for(int var = 0; var < vars.size(); ++var) {
3118                     if(!val.isEmpty())
3119                         val += " ";
3120                     val += pkgConfigFixPath(vars.at(var));
3121                 }
3122             }
3123         }
3124         t << var << "=" << val << endl;
3125     }
3126
3127     t << endl;
3128
3129     QString name = project->first("QMAKE_PKGCONFIG_NAME");
3130     if(name.isEmpty()) {
3131         name = project->first("QMAKE_ORIG_TARGET").toLower();
3132         name.replace(0, 1, name[0].toUpper());
3133     }
3134     t << "Name: " << name << endl;
3135     QString desc = project->values("QMAKE_PKGCONFIG_DESCRIPTION").join(" ");
3136     if(desc.isEmpty()) {
3137         if(name.isEmpty()) {
3138             desc = project->first("QMAKE_ORIG_TARGET").toLower();
3139             desc.replace(0, 1, desc[0].toUpper());
3140         } else {
3141             desc = name;
3142         }
3143         if(project->first("TEMPLATE") == "lib") {
3144             if(project->isActiveConfig("plugin"))
3145                desc += " Plugin";
3146             else
3147                desc += " Library";
3148         } else if(project->first("TEMPLATE") == "app") {
3149             desc += " Application";
3150         }
3151     }
3152     t << "Description: " << desc << endl;
3153     t << "Version: " << project->first("VERSION") << endl;
3154
3155     // libs
3156     t << "Libs: ";
3157     QString pkgConfiglibDir;
3158     QString pkgConfiglibName;
3159     if (target_mode == TARG_MACX_MODE && project->isActiveConfig("lib_bundle")) {
3160         pkgConfiglibDir = "-F${libdir}";
3161         QString bundle;
3162         if (!project->isEmpty("QMAKE_FRAMEWORK_BUNDLE_NAME"))
3163             bundle = unescapeFilePath(project->first("QMAKE_FRAMEWORK_BUNDLE_NAME"));
3164         else
3165             bundle = unescapeFilePath(project->first("TARGET"));
3166         int suffix = bundle.lastIndexOf(".framework");
3167         if (suffix != -1)
3168             bundle = bundle.left(suffix);
3169         pkgConfiglibName = "-framework " + bundle + " ";
3170     } else {
3171         pkgConfiglibDir = "-L${libdir}";
3172         pkgConfiglibName = "-l" + lname.left(lname.length()-Option::libtool_ext.length());
3173         if (project->isActiveConfig("shared"))
3174             pkgConfiglibName += project->first("TARGET_VERSION_EXT");
3175     }
3176     t << pkgConfiglibDir << " " << pkgConfiglibName << " " << endl;
3177
3178     QStringList libs;
3179     if(!project->isEmpty("QMAKE_INTERNAL_PRL_LIBS")) {
3180         libs = project->values("QMAKE_INTERNAL_PRL_LIBS");
3181     } else {
3182         libs << "QMAKE_LIBS"; //obvious one
3183     }
3184     libs << "QMAKE_LIBS_PRIVATE";
3185     libs << "QMAKE_LFLAGS_THREAD"; //not sure about this one, but what about things like -pthread?
3186     t << "Libs.private: ";
3187     for(QStringList::ConstIterator it = libs.begin(); it != libs.end(); ++it) {
3188         t << project->values((*it)).join(" ") << " ";
3189     }
3190     t << endl;
3191
3192     // flags
3193     // ### too many
3194     t << "Cflags: "
3195         // << var("QMAKE_CXXFLAGS") << " "
3196       << varGlue("PRL_EXPORT_DEFINES","-D"," -D"," ")
3197       << project->values("PRL_EXPORT_CXXFLAGS").join(" ")
3198       << project->values("QMAKE_PKGCONFIG_CFLAGS").join(" ")
3199         //      << varGlue("DEFINES","-D"," -D"," ")
3200       << " -I${includedir}" << endl;
3201
3202     // requires
3203     const QString requires = project->values("QMAKE_PKGCONFIG_REQUIRES").join(" ");
3204     if (!requires.isEmpty()) {
3205         t << "Requires: " << requires << endl;
3206     }
3207
3208     t << endl;
3209 }
3210
3211 QT_END_NAMESPACE