remove pointless appending of trailing dir separator under unix
[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                 t << mkdir_p_asstring(filePrefixRoot(root, tmp_dst)) << "\n\t";
1343             }
1344             t << target << endl << endl;
1345             if(!uninst.isEmpty()) {
1346                 t << "uninstall_" << (*it) << ": FORCE\n\t" << uninst.join(" ")
1347                   << "\n\t-$(DEL_DIR) " << filePrefixRoot(root, dst) << " " << endl << endl;
1348             }
1349             t << endl;
1350
1351             if(project->values((*it) + ".CONFIG").indexOf("no_default_install") == -1) {
1352                 all_installs += QString("install_") + (*it) + " ";
1353                 if(!uninst.isEmpty())
1354                     all_uninstalls += "uninstall_" + (*it) + " ";
1355             }
1356         }   else {
1357             debug_msg(1, "no definition for install %s: install target not created",(*it).toLatin1().constData());
1358         }
1359     }
1360     t << "install: " << var("INSTALLDEPS") << " " << all_installs
1361       << " FORCE\n\nuninstall: " << all_uninstalls << " " << var("UNINSTALLDEPS")
1362       << " FORCE\n\n";
1363 }
1364
1365 QString
1366 MakefileGenerator::var(const QString &var)
1367 {
1368     return val(project->values(var));
1369 }
1370
1371 QString
1372 MakefileGenerator::val(const QStringList &varList)
1373 {
1374     return valGlue(varList, "", " ", "");
1375 }
1376
1377 QString
1378 MakefileGenerator::varGlue(const QString &var, const QString &before, const QString &glue, const QString &after)
1379 {
1380     return valGlue(project->values(var), before, glue, after);
1381 }
1382
1383 QString
1384 MakefileGenerator::fileVarGlue(const QString &var, const QString &before, const QString &glue, const QString &after)
1385 {
1386     QStringList varList;
1387     foreach (const QString &val, project->values(var))
1388         varList << escapeFilePath(Option::fixPathToTargetOS(val));
1389     return valGlue(varList, before, glue, after);
1390 }
1391
1392 QString
1393 MakefileGenerator::valGlue(const QStringList &varList, const QString &before, const QString &glue, const QString &after)
1394 {
1395     QString ret;
1396     for(QStringList::ConstIterator it = varList.begin(); it != varList.end(); ++it) {
1397         if(!(*it).isEmpty()) {
1398             if(!ret.isEmpty())
1399                 ret += glue;
1400             ret += (*it);
1401         }
1402     }
1403     return ret.isEmpty() ? QString("") : before + ret + after;
1404 }
1405
1406
1407 QString
1408 MakefileGenerator::varList(const QString &var)
1409 {
1410     return valList(project->values(var));
1411 }
1412
1413 QString
1414 MakefileGenerator::valList(const QStringList &varList)
1415 {
1416     return valGlue(varList, "", " \\\n\t\t", "");
1417 }
1418
1419 QStringList
1420 MakefileGenerator::createObjectList(const QStringList &sources)
1421 {
1422     QStringList ret;
1423     QString objdir;
1424     if(!project->values("OBJECTS_DIR").isEmpty())
1425         objdir = project->first("OBJECTS_DIR");
1426     for(QStringList::ConstIterator it = sources.begin(); it != sources.end(); ++it) {
1427         QFileInfo fi(fileInfo(Option::fixPathToLocalOS((*it))));
1428         QString dir;
1429         if(objdir.isEmpty() && project->isActiveConfig("object_with_source")) {
1430             QString fName = Option::fixPathToTargetOS((*it), false);
1431             int dl = fName.lastIndexOf(Option::dir_sep);
1432             if(dl != -1)
1433                 dir = fName.left(dl + 1);
1434         } else if (project->isActiveConfig("object_parallel_to_source")) {
1435             // The source paths are relative to the output dir, but we need source-relative paths
1436             QString sourceRelativePath = fileFixify(*it, qmake_getpwd(), Option::output_dir);
1437             sourceRelativePath = Option::fixPathToTargetOS(sourceRelativePath, false);
1438
1439             if (sourceRelativePath.startsWith(".." + Option::dir_sep))
1440                 sourceRelativePath = fileFixify(sourceRelativePath, FileFixifyAbsolute);
1441
1442             if (QDir::isAbsolutePath(sourceRelativePath))
1443                 sourceRelativePath.remove(0, sourceRelativePath.indexOf(Option::dir_sep) + 1);
1444
1445             dir = objdir; // We still respect OBJECTS_DIR
1446
1447             int lastDirSepPosition = sourceRelativePath.lastIndexOf(Option::dir_sep);
1448             if (lastDirSepPosition != -1)
1449                 dir += sourceRelativePath.leftRef(lastDirSepPosition + 1);
1450
1451             if (!noIO()) {
1452                 // Ensure that the final output directory of each object exists
1453                 QString outRelativePath = fileFixify(dir, qmake_getpwd(), Option::output_dir);
1454                 if (!mkdir(outRelativePath))
1455                     warn_msg(WarnLogic, "Cannot create directory '%s'", outRelativePath.toLatin1().constData());
1456             }
1457         } else {
1458             dir = objdir;
1459         }
1460         ret.append(dir + fi.completeBaseName() + Option::obj_ext);
1461     }
1462     return ret;
1463 }
1464
1465 ReplaceExtraCompilerCacheKey::ReplaceExtraCompilerCacheKey(const QString &v, const QStringList &i, const QStringList &o)
1466 {
1467     static QString doubleColon = QLatin1String("::");
1468
1469     hash = 0;
1470     pwd = qmake_getpwd();
1471     var = v;
1472     {
1473         QStringList il = i;
1474         il.sort();
1475         in = il.join(doubleColon);
1476     }
1477     {
1478         QStringList ol = o;
1479         ol.sort();
1480         out = ol.join(doubleColon);
1481     }
1482 }
1483
1484 bool ReplaceExtraCompilerCacheKey::operator==(const ReplaceExtraCompilerCacheKey &f) const
1485 {
1486     return (hashCode() == f.hashCode() &&
1487             f.in == in &&
1488             f.out == out &&
1489             f.var == var &&
1490             f.pwd == pwd);
1491 }
1492
1493
1494 QString
1495 MakefileGenerator::replaceExtraCompilerVariables(const QString &orig_var, const QStringList &in, const QStringList &out)
1496 {
1497     //lazy cache
1498     ReplaceExtraCompilerCacheKey cacheKey(orig_var, in, out);
1499     QString cacheVal = extraCompilerVariablesCache.value(cacheKey);
1500     if(!cacheVal.isNull())
1501         return cacheVal;
1502
1503     //do the work
1504     QString ret = orig_var;
1505     QRegExp reg_var("\\$\\{.*\\}");
1506     reg_var.setMinimal(true);
1507     for(int rep = 0; (rep = reg_var.indexIn(ret, rep)) != -1; ) {
1508         QStringList val;
1509         const QString var = ret.mid(rep + 2, reg_var.matchedLength() - 3);
1510         bool filePath = false;
1511         if(val.isEmpty() && var.startsWith(QLatin1String("QMAKE_VAR_"))) {
1512             const QString varname = var.mid(10);
1513             val += project->values(varname);
1514         }
1515         if(val.isEmpty() && var.startsWith(QLatin1String("QMAKE_VAR_FIRST_"))) {
1516             const QString varname = var.mid(16);
1517             val += project->first(varname);
1518         }
1519
1520         if(val.isEmpty() && !in.isEmpty()) {
1521             if(var.startsWith(QLatin1String("QMAKE_FUNC_FILE_IN_"))) {
1522                 filePath = true;
1523                 const QString funcname = var.mid(19);
1524                 val += project->expand(funcname, QList<QStringList>() << in);
1525             } else if(var == QLatin1String("QMAKE_FILE_BASE") || var == QLatin1String("QMAKE_FILE_IN_BASE")) {
1526                 //filePath = true;
1527                 for(int i = 0; i < in.size(); ++i) {
1528                     QFileInfo fi(fileInfo(Option::fixPathToLocalOS(in.at(i))));
1529                     QString base = fi.completeBaseName();
1530                     if(base.isNull())
1531                         base = fi.fileName();
1532                     val += base;
1533                 }
1534             } else if(var == QLatin1String("QMAKE_FILE_EXT")) {
1535                 filePath = true;
1536                 for(int i = 0; i < in.size(); ++i) {
1537                     QFileInfo fi(fileInfo(Option::fixPathToLocalOS(in.at(i))));
1538                     QString ext;
1539                     // Ensure complementarity with QMAKE_FILE_BASE
1540                     int baseLen = fi.completeBaseName().length();
1541                     if(baseLen == 0)
1542                         ext = fi.fileName();
1543                     else
1544                         ext = fi.fileName().remove(0, baseLen);
1545                     val += ext;
1546                 }
1547             } else if(var == QLatin1String("QMAKE_FILE_PATH") || var == QLatin1String("QMAKE_FILE_IN_PATH")) {
1548                 filePath = true;
1549                 for(int i = 0; i < in.size(); ++i)
1550                     val += fileInfo(Option::fixPathToLocalOS(in.at(i))).path();
1551             } else if(var == QLatin1String("QMAKE_FILE_NAME") || var == QLatin1String("QMAKE_FILE_IN")) {
1552                 filePath = true;
1553                 for(int i = 0; i < in.size(); ++i)
1554                     val += fileInfo(Option::fixPathToLocalOS(in.at(i))).filePath();
1555
1556             }
1557         }
1558         if(val.isEmpty() && !out.isEmpty()) {
1559             if(var.startsWith(QLatin1String("QMAKE_FUNC_FILE_OUT_"))) {
1560                 filePath = true;
1561                 const QString funcname = var.mid(20);
1562                 val += project->expand(funcname, QList<QStringList>() << out);
1563             } else if(var == QLatin1String("QMAKE_FILE_OUT")) {
1564                 filePath = true;
1565                 for(int i = 0; i < out.size(); ++i)
1566                     val += fileInfo(Option::fixPathToLocalOS(out.at(i))).filePath();
1567             } else if(var == QLatin1String("QMAKE_FILE_OUT_BASE")) {
1568                 //filePath = true;
1569                 for(int i = 0; i < out.size(); ++i) {
1570                     QFileInfo fi(fileInfo(Option::fixPathToLocalOS(out.at(i))));
1571                     QString base = fi.completeBaseName();
1572                     if(base.isNull())
1573                         base = fi.fileName();
1574                     val += base;
1575                 }
1576             }
1577         }
1578         if(val.isEmpty() && var.startsWith(QLatin1String("QMAKE_FUNC_"))) {
1579             const QString funcname = var.mid(11);
1580             val += project->expand(funcname, QList<QStringList>() << in << out);
1581         }
1582
1583         if(!val.isEmpty()) {
1584             QString fullVal;
1585             if(filePath) {
1586                 for(int i = 0; i < val.size(); ++i) {
1587                     const QString file = Option::fixPathToTargetOS(unescapeFilePath(val.at(i)), false);
1588                     if(!fullVal.isEmpty())
1589                         fullVal += " ";
1590                     fullVal += escapeFilePath(file);
1591                 }
1592             } else {
1593                 fullVal = val.join(" ");
1594             }
1595             ret.replace(rep, reg_var.matchedLength(), fullVal);
1596             rep += fullVal.length();
1597         } else {
1598             rep += reg_var.matchedLength();
1599         }
1600     }
1601
1602     //cache the value
1603     extraCompilerVariablesCache.insert(cacheKey, ret);
1604     return ret;
1605 }
1606
1607 bool
1608 MakefileGenerator::verifyExtraCompiler(const QString &comp, const QString &file_unfixed)
1609 {
1610     if(noIO())
1611         return false;
1612     const QString file = Option::fixPathToLocalOS(file_unfixed);
1613
1614     if(project->values(comp + ".CONFIG").indexOf("moc_verify") != -1) {
1615         if(!file.isNull()) {
1616             QMakeSourceFileInfo::addSourceFile(file, QMakeSourceFileInfo::SEEK_MOCS);
1617             if(!mocable(file)) {
1618                 return false;
1619             } else {
1620                 project->values("MOCABLES").append(file);
1621             }
1622         }
1623     } else if(project->values(comp + ".CONFIG").indexOf("function_verify") != -1) {
1624         QString tmp_out = project->values(comp + ".output").first();
1625         if(tmp_out.isEmpty())
1626             return false;
1627         QStringList verify_function = project->values(comp + ".verify_function");
1628         if(verify_function.isEmpty())
1629             return false;
1630
1631         for(int i = 0; i < verify_function.size(); ++i) {
1632             bool invert = false;
1633             QString verify = verify_function.at(i);
1634             if(verify.at(0) == QLatin1Char('!')) {
1635                 invert = true;
1636                 verify = verify.mid(1);
1637             }
1638
1639             if(project->values(comp + ".CONFIG").indexOf("combine") != -1) {
1640                 bool pass = project->test(verify, QList<QStringList>() << QStringList(tmp_out) << QStringList(file));
1641                 if(invert)
1642                     pass = !pass;
1643                 if(!pass)
1644                     return false;
1645             } else {
1646                 const QStringList &tmp = project->values(comp + ".input");
1647                 for (QStringList::ConstIterator it = tmp.begin(); it != tmp.end(); ++it) {
1648                     const QStringList &inputs = project->values((*it));
1649                     for (QStringList::ConstIterator input = inputs.begin(); input != inputs.end(); ++input) {
1650                         if((*input).isEmpty())
1651                             continue;
1652                         QString in = fileFixify(Option::fixPathToTargetOS((*input), false));
1653                         if(in == file) {
1654                             bool pass = project->test(verify,
1655                                                       QList<QStringList>() << QStringList(replaceExtraCompilerVariables(tmp_out, (*input), QString())) <<
1656                                                       QStringList(file));
1657                             if(invert)
1658                                 pass = !pass;
1659                             if(!pass)
1660                                 return false;
1661                             break;
1662                         }
1663                     }
1664                 }
1665             }
1666         }
1667     } else if(project->values(comp + ".CONFIG").indexOf("verify") != -1) {
1668         QString tmp_out = project->values(comp + ".output").first();
1669         if(tmp_out.isEmpty())
1670             return false;
1671         QString tmp_cmd;
1672         if(!project->isEmpty(comp + ".commands")) {
1673             int argv0 = -1;
1674             QStringList cmdline = project->values(comp + ".commands");
1675             for(int i = 0; i < cmdline.count(); ++i) {
1676                 if(!cmdline.at(i).contains('=')) {
1677                     argv0 = i;
1678                     break;
1679                 }
1680             }
1681             if(argv0 != -1) {
1682                 cmdline[argv0] = Option::fixPathToTargetOS(cmdline.at(argv0), false);
1683                 tmp_cmd = cmdline.join(" ");
1684             }
1685         }
1686
1687         if(project->values(comp + ".CONFIG").indexOf("combine") != -1) {
1688             QString cmd = replaceExtraCompilerVariables(tmp_cmd, QString(), tmp_out);
1689             if(system(cmd.toLatin1().constData()))
1690                 return false;
1691         } else {
1692             const QStringList &tmp = project->values(comp + ".input");
1693             for (QStringList::ConstIterator it = tmp.begin(); it != tmp.end(); ++it) {
1694                 const QStringList &inputs = project->values((*it));
1695                 for (QStringList::ConstIterator input = inputs.begin(); input != inputs.end(); ++input) {
1696                     if((*input).isEmpty())
1697                         continue;
1698                     QString in = fileFixify(Option::fixPathToTargetOS((*input), false));
1699                     if(in == file) {
1700                         QString out = replaceExtraCompilerVariables(tmp_out, (*input), QString());
1701                         QString cmd = replaceExtraCompilerVariables(tmp_cmd, in, out);
1702                         if(system(cmd.toLatin1().constData()))
1703                             return false;
1704                         break;
1705                     }
1706                 }
1707             }
1708         }
1709     }
1710     return true;
1711 }
1712
1713 void
1714 MakefileGenerator::writeExtraTargets(QTextStream &t)
1715 {
1716     const QStringList &qut = project->values("QMAKE_EXTRA_TARGETS");
1717     for (QStringList::ConstIterator it = qut.begin(); it != qut.end(); ++it) {
1718         QString targ = var((*it) + ".target"),
1719                  cmd = var((*it) + ".commands"), deps;
1720         if(targ.isEmpty())
1721             targ = (*it);
1722         const QStringList &deplist = project->values((*it) + ".depends");
1723         for (QStringList::ConstIterator dep_it = deplist.begin(); dep_it != deplist.end(); ++dep_it) {
1724             QString dep = var((*dep_it) + ".target");
1725             if(dep.isEmpty())
1726                 dep = (*dep_it);
1727             deps += " " + escapeDependencyPath(dep);
1728         }
1729         if(project->values((*it) + ".CONFIG").indexOf("fix_target") != -1)
1730             targ = fileFixify(targ, Option::output_dir, Option::output_dir);
1731         if (project->values((*it) + ".CONFIG").indexOf("phony") != -1)
1732             deps += QLatin1String(" FORCE");
1733         t << escapeDependencyPath(targ) << ":" << deps;
1734         if(!cmd.isEmpty())
1735             t << "\n\t" << cmd;
1736         t << endl << endl;
1737     }
1738 }
1739
1740 void
1741 MakefileGenerator::writeExtraCompilerTargets(QTextStream &t)
1742 {
1743     QString clean_targets;
1744     const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
1745     for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
1746         QString tmp_out = fileFixify(project->values((*it) + ".output").first(),
1747                                      Option::output_dir, Option::output_dir);
1748         QString tmp_cmd;
1749         if(!project->isEmpty((*it) + ".commands")) {
1750             QStringList cmdline = project->values((*it) + ".commands");
1751             int argv0 = findExecutable(cmdline);
1752             if(argv0 != -1) {
1753                 cmdline[argv0] = escapeFilePath(Option::fixPathToTargetOS(cmdline.at(argv0), false));
1754                 tmp_cmd = cmdline.join(" ");
1755             }
1756         }
1757         QStringList tmp_dep = project->values((*it) + ".depends");
1758         QString tmp_dep_cmd;
1759         QString dep_cd_cmd;
1760         if(!project->isEmpty((*it) + ".depend_command")) {
1761             int argv0 = -1;
1762             QStringList cmdline = project->values((*it) + ".depend_command");
1763             for(int i = 0; i < cmdline.count(); ++i) {
1764                 if(!cmdline.at(i).contains('=')) {
1765                     argv0 = i;
1766                     break;
1767                 }
1768             }
1769             if(argv0 != -1) {
1770                 const QString c = Option::fixPathToLocalOS(cmdline.at(argv0), true);
1771                 if(exists(c)) {
1772                     cmdline[argv0] = escapeFilePath(Option::fixPathToLocalOS(cmdline.at(argv0), false));
1773                 } else {
1774                     cmdline[argv0] = escapeFilePath(cmdline.at(argv0));
1775                 }
1776                 QFileInfo cmdFileInfo(cmdline[argv0]);
1777                 if (!cmdFileInfo.isAbsolute() || cmdFileInfo.exists())
1778                     tmp_dep_cmd = cmdline.join(" ");
1779             }
1780             dep_cd_cmd = QLatin1String("cd ")
1781                  + escapeFilePath(Option::fixPathToLocalOS(Option::output_dir, false))
1782                  + QLatin1String(" && ");
1783         }
1784         const QStringList &vars = project->values((*it) + ".variables");
1785         if(tmp_out.isEmpty() || tmp_cmd.isEmpty())
1786             continue;
1787         QStringList tmp_inputs;
1788         {
1789             const QStringList &comp_inputs = project->values((*it) + ".input");
1790             for(QStringList::ConstIterator it2 = comp_inputs.begin(); it2 != comp_inputs.end(); ++it2) {
1791                 const QStringList &tmp = project->values((*it2));
1792                 for(QStringList::ConstIterator input = tmp.begin(); input != tmp.end(); ++input) {
1793                     QString in = Option::fixPathToTargetOS((*input), false);
1794                     if(verifyExtraCompiler((*it), in))
1795                         tmp_inputs.append((*input));
1796                 }
1797             }
1798         }
1799
1800         t << "compiler_" << (*it) << "_make_all:";
1801         if(project->values((*it) + ".CONFIG").indexOf("combine") != -1) {
1802             // compilers with a combined input only have one output
1803             QString input = project->values((*it) + ".output").first();
1804             t << " " << escapeDependencyPath(replaceExtraCompilerVariables(tmp_out, input, QString()));
1805         } else {
1806             for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input) {
1807                 QString in = Option::fixPathToTargetOS((*input), false);
1808                 t << " " << escapeDependencyPath(replaceExtraCompilerVariables(tmp_out, (*input), QString()));
1809             }
1810         }
1811         t << endl;
1812
1813         if(project->values((*it) + ".CONFIG").indexOf("no_clean") == -1) {
1814             QString tmp_clean = project->values((*it) + ".clean").join(" ");
1815             QString tmp_clean_cmds = project->values((*it) + ".clean_commands").join(" ");
1816             if(!tmp_inputs.isEmpty())
1817                 clean_targets += QString("compiler_" + (*it) + "_clean ");
1818             t << "compiler_" << (*it) << "_clean:";
1819             bool wrote_clean_cmds = false, wrote_clean = false;
1820             if(tmp_clean_cmds.isEmpty()) {
1821                 wrote_clean_cmds = true;
1822             } else if(tmp_clean_cmds.indexOf("${QMAKE_") == -1) {
1823                 t << "\n\t" << tmp_clean_cmds;
1824                 wrote_clean_cmds = true;
1825             }
1826             if(tmp_clean.isEmpty())
1827                 tmp_clean = tmp_out;
1828             if(tmp_clean.indexOf("${QMAKE_") == -1) {
1829                 t << "\n\t" << "-$(DEL_FILE) " << tmp_clean;
1830                 wrote_clean = true;
1831             }
1832             if(!wrote_clean_cmds || !wrote_clean) {
1833                 QStringList cleans;
1834                 const QString del_statement("-$(DEL_FILE)");
1835                 if(!wrote_clean) {
1836                     if(project->isActiveConfig("no_delete_multiple_files")) {
1837                         for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input)
1838                             cleans.append(" " + replaceExtraCompilerVariables(tmp_clean, (*input),
1839                                                 replaceExtraCompilerVariables(tmp_out, (*input), QString())));
1840                     } else {
1841                         QString files, file;
1842                         const int commandlineLimit = 2047; // NT limit, expanded
1843                         for(int input = 0; input < tmp_inputs.size(); ++input) {
1844                             file = " " + replaceExtraCompilerVariables(tmp_clean, tmp_inputs.at(input),
1845                                            replaceExtraCompilerVariables(tmp_out, tmp_inputs.at(input), QString()));
1846                             if(del_statement.length() + files.length() +
1847                                qMax(fixEnvVariables(file).length(), file.length()) > commandlineLimit) {
1848                                 cleans.append(files);
1849                                 files.clear();
1850                             }
1851                             files += file;
1852                         }
1853                         if(!files.isEmpty())
1854                             cleans.append(files);
1855                     }
1856                 }
1857                 if(!cleans.isEmpty())
1858                     t << valGlue(cleans, "\n\t" + del_statement, "\n\t" + del_statement, "");
1859                 if(!wrote_clean_cmds) {
1860                     for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input) {
1861                         t << "\n\t" << replaceExtraCompilerVariables(tmp_clean_cmds, (*input),
1862                                          replaceExtraCompilerVariables(tmp_out, (*input), QString()));
1863                     }
1864                 }
1865             }
1866             t << endl;
1867         }
1868         if(project->values((*it) + ".CONFIG").indexOf("combine") != -1) {
1869             if(tmp_out.indexOf("${QMAKE_") != -1) {
1870                 warn_msg(WarnLogic, "QMAKE_EXTRA_COMPILERS(%s) with combine has variable output.",
1871                          (*it).toLatin1().constData());
1872                 continue;
1873             }
1874             QStringList deps, inputs;
1875             if(!tmp_dep.isEmpty())
1876                 deps += fileFixify(tmp_dep, Option::output_dir, Option::output_dir);
1877             for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input) {
1878                 deps += findDependencies((*input));
1879                 inputs += Option::fixPathToTargetOS((*input), false);
1880                 if(!tmp_dep_cmd.isEmpty() && doDepends()) {
1881                     char buff[256];
1882                     QString dep_cmd = replaceExtraCompilerVariables(tmp_dep_cmd, (*input),
1883                                                                     tmp_out);
1884                     dep_cmd = dep_cd_cmd + fixEnvVariables(dep_cmd);
1885                     if(FILE *proc = QT_POPEN(dep_cmd.toLatin1().constData(), "r")) {
1886                         QString indeps;
1887                         while(!feof(proc)) {
1888                             int read_in = (int)fread(buff, 1, 255, proc);
1889                             if(!read_in)
1890                                 break;
1891                             indeps += QByteArray(buff, read_in);
1892                         }
1893                         QT_PCLOSE(proc);
1894                         if(!indeps.isEmpty()) {
1895                             QStringList dep_cmd_deps = indeps.replace('\n', ' ').simplified().split(' ');
1896                             for(int i = 0; i < dep_cmd_deps.count(); ++i) {
1897                                 QString &file = dep_cmd_deps[i];
1898                                 if(!exists(file)) {
1899                                     QString localFile;
1900                                     QList<QMakeLocalFileName> depdirs = QMakeSourceFileInfo::dependencyPaths();
1901                                     for(QList<QMakeLocalFileName>::Iterator it = depdirs.begin();
1902                                         it != depdirs.end(); ++it) {
1903                                         if(exists((*it).real() + Option::dir_sep + file)) {
1904                                             localFile = (*it).local() + Option::dir_sep + file;
1905                                             break;
1906                                         }
1907                                     }
1908                                     file = localFile;
1909                                 }
1910                                 if(!file.isEmpty())
1911                                     file = fileFixify(file);
1912                             }
1913                             deps += dep_cmd_deps;
1914                         }
1915                     }
1916                 }
1917             }
1918             for(int i = 0; i < inputs.size(); ) {
1919                 if(tmp_out == inputs.at(i))
1920                     inputs.removeAt(i);
1921                 else
1922                     ++i;
1923             }
1924             for(int i = 0; i < deps.size(); ) {
1925                 if(tmp_out == deps.at(i))
1926                     deps.removeAt(i);
1927                 else
1928                     ++i;
1929             }
1930             if (inputs.isEmpty())
1931                 continue;
1932
1933             QString cmd = replaceExtraCompilerVariables(tmp_cmd, escapeFilePaths(inputs), QStringList(tmp_out));
1934             t << escapeDependencyPath(tmp_out) << ":";
1935             // compiler.CONFIG+=explicit_dependencies means that ONLY compiler.depends gets to cause Makefile dependencies
1936             if(project->values((*it) + ".CONFIG").indexOf("explicit_dependencies") != -1) {
1937                 t << " " << valList(escapeDependencyPaths(fileFixify(tmp_dep, Option::output_dir, Option::output_dir)));
1938             } else {
1939                 t << " " << valList(escapeDependencyPaths(inputs)) << " " << valList(escapeDependencyPaths(deps));
1940             }
1941             t << "\n\t" << cmd << endl << endl;
1942             continue;
1943         }
1944         for(QStringList::ConstIterator input = tmp_inputs.begin(); input != tmp_inputs.end(); ++input) {
1945             QString in = Option::fixPathToTargetOS((*input), false);
1946             QStringList deps = findDependencies((*input));
1947             deps += escapeDependencyPath(in);
1948             QString out = replaceExtraCompilerVariables(tmp_out, (*input), QString());
1949             if(!tmp_dep.isEmpty()) {
1950                 QStringList pre_deps = fileFixify(tmp_dep, Option::output_dir, Option::output_dir);
1951                 for(int i = 0; i < pre_deps.size(); ++i)
1952                    deps += replaceExtraCompilerVariables(pre_deps.at(i), (*input), out);
1953             }
1954             QString cmd = replaceExtraCompilerVariables(tmp_cmd, (*input), out);
1955             // NOTE: The var -> QMAKE_COMP_var replace feature is unsupported, do not use!
1956             for(QStringList::ConstIterator it3 = vars.constBegin(); it3 != vars.constEnd(); ++it3)
1957                 cmd.replace("$(" + (*it3) + ")", "$(QMAKE_COMP_" + (*it3)+")");
1958             if(!tmp_dep_cmd.isEmpty() && doDepends()) {
1959                 char buff[256];
1960                 QString dep_cmd = replaceExtraCompilerVariables(tmp_dep_cmd, (*input), out);
1961                 dep_cmd = dep_cd_cmd + fixEnvVariables(dep_cmd);
1962                 if(FILE *proc = QT_POPEN(dep_cmd.toLatin1().constData(), "r")) {
1963                     QString indeps;
1964                     while(!feof(proc)) {
1965                         int read_in = (int)fread(buff, 1, 255, proc);
1966                         if(!read_in)
1967                             break;
1968                         indeps += QByteArray(buff, read_in);
1969                     }
1970                     QT_PCLOSE(proc);
1971                     if(!indeps.isEmpty()) {
1972                         QStringList dep_cmd_deps = indeps.replace('\n', ' ').simplified().split(' ');
1973                         for(int i = 0; i < dep_cmd_deps.count(); ++i) {
1974                             QString &file = dep_cmd_deps[i];
1975                             if(!exists(file)) {
1976                                 QString localFile;
1977                                 QList<QMakeLocalFileName> depdirs = QMakeSourceFileInfo::dependencyPaths();
1978                                 for(QList<QMakeLocalFileName>::Iterator it = depdirs.begin();
1979                                     it != depdirs.end(); ++it) {
1980                                     if(exists((*it).real() + Option::dir_sep + file)) {
1981                                         localFile = (*it).local() + Option::dir_sep + file;
1982                                         break;
1983                                     }
1984                                 }
1985                                 file = localFile;
1986                             }
1987                             if(!file.isEmpty())
1988                                 file = fileFixify(file);
1989                         }
1990                         deps += dep_cmd_deps;
1991                     }
1992                 }
1993                 //use the depend system to find includes of these included files
1994                 QStringList inc_deps;
1995                 for(int i = 0; i < deps.size(); ++i) {
1996                     const QString dep = deps.at(i);
1997                     if(QFile::exists(dep)) {
1998                         SourceFileType type = TYPE_UNKNOWN;
1999                         if(type == TYPE_UNKNOWN) {
2000                             for(QStringList::Iterator cit = Option::c_ext.begin();
2001                                 cit != Option::c_ext.end(); ++cit) {
2002                                 if(dep.endsWith((*cit))) {
2003                                    type = TYPE_C;
2004                                    break;
2005                                 }
2006                             }
2007                         }
2008                         if(type == TYPE_UNKNOWN) {
2009                             for(QStringList::Iterator cppit = Option::cpp_ext.begin();
2010                                 cppit != Option::cpp_ext.end(); ++cppit) {
2011                                 if(dep.endsWith((*cppit))) {
2012                                     type = TYPE_C;
2013                                     break;
2014                                 }
2015                             }
2016                         }
2017                         if(type == TYPE_UNKNOWN) {
2018                             for(QStringList::Iterator hit = Option::h_ext.begin();
2019                                 type == TYPE_UNKNOWN && hit != Option::h_ext.end(); ++hit) {
2020                                 if(dep.endsWith((*hit))) {
2021                                     type = TYPE_C;
2022                                     break;
2023                                 }
2024                             }
2025                         }
2026                         if(type != TYPE_UNKNOWN) {
2027                             if(!QMakeSourceFileInfo::containsSourceFile(dep, type))
2028                                 QMakeSourceFileInfo::addSourceFile(dep, type);
2029                             inc_deps += QMakeSourceFileInfo::dependencies(dep);
2030                         }
2031                     }
2032                 }
2033                 deps += inc_deps;
2034             }
2035             for(int i = 0; i < deps.size(); ) {
2036                 QString &dep = deps[i];
2037                 dep = Option::fixPathToTargetOS(unescapeFilePath(dep), false);
2038                 if(out == dep)
2039                     deps.removeAt(i);
2040                 else
2041                     ++i;
2042             }
2043             t << escapeDependencyPath(out) << ": " << valList(escapeDependencyPaths(deps)) << "\n\t"
2044               << cmd << endl << endl;
2045         }
2046     }
2047     t << "compiler_clean: " << clean_targets << endl << endl;
2048 }
2049
2050 void
2051 MakefileGenerator::writeExtraCompilerVariables(QTextStream &t)
2052 {
2053     bool first = true;
2054     const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
2055     for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
2056         const QStringList &vars = project->values((*it) + ".variables");
2057         for(QStringList::ConstIterator varit = vars.begin(); varit != vars.end(); ++varit) {
2058             if(first) {
2059                 t << "\n####### Custom Compiler Variables" << endl;
2060                 first = false;
2061             }
2062             t << "QMAKE_COMP_" << (*varit) << " = "
2063               << valList(project->values((*varit))) << endl;
2064         }
2065     }
2066     if(!first)
2067         t << endl;
2068 }
2069
2070 void
2071 MakefileGenerator::writeExtraVariables(QTextStream &t)
2072 {
2073     t << endl;
2074
2075     QStringList outlist;
2076     const QHash<QString, QStringList> &vars = project->variables();
2077     const QStringList &exports = project->values("QMAKE_EXTRA_VARIABLES");
2078     for (QHash<QString, QStringList>::ConstIterator it = vars.begin(); it != vars.end(); ++it) {
2079         for (QStringList::ConstIterator exp_it = exports.begin(); exp_it != exports.end(); ++exp_it) {
2080             QRegExp rx((*exp_it), Qt::CaseInsensitive, QRegExp::Wildcard);
2081             if (rx.exactMatch(it.key()))
2082                 outlist << ("EXPORT_" + it.key() + " = " + it.value().join(" "));
2083         }
2084     }
2085     if (!outlist.isEmpty()) {
2086         t << "####### Custom Variables" << endl;
2087         t << outlist.join("\n") << endl << endl;
2088     }
2089 }
2090
2091 bool
2092 MakefileGenerator::writeStubMakefile(QTextStream &t)
2093 {
2094     t << "QMAKE    = " << var("QMAKE_QMAKE") << endl;
2095     const QStringList &qut = project->values("QMAKE_EXTRA_TARGETS");
2096     for(QStringList::ConstIterator it = qut.begin(); it != qut.end(); ++it)
2097         t << *it << " ";
2098     //const QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
2099     t << "first all clean install distclean uninstall: " << "qmake" << endl
2100       << "qmake_all:" << endl;
2101     writeMakeQmake(t);
2102     t << "FORCE:" << endl << endl;
2103     return true;
2104 }
2105
2106 bool
2107 MakefileGenerator::writeMakefile(QTextStream &t)
2108 {
2109     t << "####### Compile" << endl << endl;
2110     writeObj(t, "SOURCES");
2111     writeObj(t, "GENERATED_SOURCES");
2112
2113     t << "####### Install" << endl << endl;
2114     writeInstalls(t, "INSTALLS");
2115
2116     t << "FORCE:" << endl << endl;
2117     return true;
2118 }
2119
2120 QString MakefileGenerator::fixifySpecdir(const QString &spec, const QString &outdir)
2121 {
2122     if (QFileInfo(spec).isAbsolute())
2123         return fileFixify(spec, outdir);
2124     return spec;
2125 }
2126
2127 QString MakefileGenerator::buildArgs(const QString &outdir)
2128 {
2129     QString ret;
2130     //special variables
2131     if(!project->isEmpty("QMAKE_ABSOLUTE_SOURCE_PATH"))
2132         ret += " QMAKE_ABSOLUTE_SOURCE_PATH=" + escapeFilePath(project->first("QMAKE_ABSOLUTE_SOURCE_PATH"));
2133
2134     //warnings
2135     else if(Option::warn_level == WarnNone)
2136         ret += " -Wnone";
2137     else if(Option::warn_level == WarnAll)
2138         ret += " -Wall";
2139     else if(Option::warn_level & WarnParser)
2140         ret += " -Wparser";
2141     //other options
2142     if(!Option::user_template.isEmpty())
2143         ret += " -t " + Option::user_template;
2144     if(!Option::user_template_prefix.isEmpty())
2145         ret += " -tp " + Option::user_template_prefix;
2146     if(!Option::mkfile::do_cache)
2147         ret += " -nocache";
2148     if(!Option::mkfile::do_deps)
2149         ret += " -nodepend";
2150     if(!Option::mkfile::do_dep_heuristics)
2151         ret += " -nodependheuristics";
2152     if(!Option::mkfile::qmakespec_commandline.isEmpty())
2153         ret += " -spec " + fixifySpecdir(Option::mkfile::qmakespec, outdir);
2154     if (!Option::mkfile::xqmakespec_commandline.isEmpty())
2155         ret += " -xspec " + fixifySpecdir(Option::mkfile::xqmakespec, outdir);
2156
2157     //arguments
2158     for(QStringList::Iterator it = Option::before_user_vars.begin();
2159         it != Option::before_user_vars.end(); ++it) {
2160         if((*it).left(qstrlen("QMAKE_ABSOLUTE_SOURCE_PATH")) != "QMAKE_ABSOLUTE_SOURCE_PATH")
2161             ret += " " + escapeFilePath((*it));
2162     }
2163     if(Option::after_user_vars.count()) {
2164         ret += " -after ";
2165         for(QStringList::Iterator it = Option::after_user_vars.begin();
2166             it != Option::after_user_vars.end(); ++it) {
2167             if((*it).left(qstrlen("QMAKE_ABSOLUTE_SOURCE_PATH")) != "QMAKE_ABSOLUTE_SOURCE_PATH")
2168                 ret += " " + escapeFilePath((*it));
2169         }
2170     }
2171     return ret;
2172 }
2173
2174 //could get stored argv, but then it would have more options than are
2175 //probably necesary this will try to guess the bare minimum..
2176 QString MakefileGenerator::build_args(const QString &outdir)
2177 {
2178     QString ret = "$(QMAKE)";
2179
2180     // general options and arguments
2181     ret += buildArgs(outdir);
2182
2183     //output
2184     QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
2185     if(!ofile.isEmpty() && ofile != project->first("QMAKE_MAKEFILE"))
2186         ret += " -o " + escapeFilePath(ofile);
2187
2188     //inputs
2189     ret += " " + escapeFilePath(fileFixify(project->projectFile(), outdir));
2190
2191     return ret;
2192 }
2193
2194 void
2195 MakefileGenerator::writeHeader(QTextStream &t)
2196 {
2197     t << "#############################################################################" << endl;
2198     t << "# Makefile for building: " << escapeFilePath(var("TARGET")) << endl;
2199     t << "# Generated by qmake (" << qmake_version() << ") (Qt " << QT_VERSION_STR << ") on: ";
2200     t << QDateTime::currentDateTime().toString() << endl;
2201     t << "# Project:  " << fileFixify(project->projectFile()) << endl;
2202     t << "# Template: " << var("TEMPLATE") << endl;
2203     if(!project->isActiveConfig("build_pass"))
2204         t << "# Command: " << build_args().replace("$(QMAKE)", var("QMAKE_QMAKE")) << endl;
2205     t << "#############################################################################" << endl;
2206     t << endl;
2207 }
2208
2209 QList<MakefileGenerator::SubTarget*>
2210 MakefileGenerator::findSubDirsSubTargets() const
2211 {
2212     QList<SubTarget*> targets;
2213     {
2214         const QStringList subdirs = project->values("SUBDIRS");
2215         for(int subdir = 0; subdir < subdirs.size(); ++subdir) {
2216             QString fixedSubdir = subdirs[subdir];
2217             fixedSubdir = fixedSubdir.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2218
2219             SubTarget *st = new SubTarget;
2220             st->name = subdirs[subdir];
2221             targets.append(st);
2222
2223             bool fromFile = false;
2224             QString file = subdirs[subdir];
2225             if(!project->isEmpty(fixedSubdir + ".file")) {
2226                 if(!project->isEmpty(fixedSubdir + ".subdir"))
2227                     warn_msg(WarnLogic, "Cannot assign both file and subdir for subdir %s",
2228                              subdirs[subdir].toLatin1().constData());
2229                 file = project->first(fixedSubdir + ".file");
2230                 fromFile = true;
2231             } else if(!project->isEmpty(fixedSubdir + ".subdir")) {
2232                 file = project->first(fixedSubdir + ".subdir");
2233                 fromFile = false;
2234             } else {
2235                 fromFile = file.endsWith(Option::pro_ext);
2236             }
2237             file = Option::fixPathToTargetOS(file);
2238
2239             if(fromFile) {
2240                 int slsh = file.lastIndexOf(Option::dir_sep);
2241                 if(slsh != -1) {
2242                     st->in_directory = file.left(slsh+1);
2243                     st->profile = file.mid(slsh+1);
2244                 } else {
2245                     st->profile = file;
2246                 }
2247             } else {
2248                 if(!file.isEmpty() && !project->isActiveConfig("subdir_first_pro"))
2249                     st->profile = file.section(Option::dir_sep, -1) + Option::pro_ext;
2250                 st->in_directory = file;
2251             }
2252             while(st->in_directory.endsWith(Option::dir_sep))
2253                 st->in_directory.chop(1);
2254             if(fileInfo(st->in_directory).isRelative())
2255                 st->out_directory = st->in_directory;
2256             else
2257                 st->out_directory = fileFixify(st->in_directory, qmake_getpwd(), Option::output_dir);
2258             if(!project->isEmpty(fixedSubdir + ".makefile")) {
2259                 st->makefile = project->first(fixedSubdir + ".makefile");
2260             } else {
2261                 st->makefile = "Makefile";
2262                 if(!st->profile.isEmpty()) {
2263                     QString basename = st->in_directory;
2264                     int new_slsh = basename.lastIndexOf(Option::dir_sep);
2265                     if(new_slsh != -1)
2266                         basename = basename.mid(new_slsh+1);
2267                     if(st->profile != basename + Option::pro_ext)
2268                         st->makefile += "." + st->profile.left(st->profile.length() - Option::pro_ext.length());
2269                 }
2270             }
2271             if(!project->isEmpty(fixedSubdir + ".depends")) {
2272                 const QStringList depends = project->values(fixedSubdir + ".depends");
2273                 for(int depend = 0; depend < depends.size(); ++depend) {
2274                     bool found = false;
2275                     for(int subDep = 0; subDep < subdirs.size(); ++subDep) {
2276                         if(subdirs[subDep] == depends.at(depend)) {
2277                             QString fixedSubDep = subdirs[subDep];
2278                             fixedSubDep = fixedSubDep.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2279                             if(!project->isEmpty(fixedSubDep + ".target")) {
2280                                 st->depends += project->first(fixedSubDep + ".target");
2281                             } else {
2282                                 QString d = Option::fixPathToLocalOS(subdirs[subDep]);
2283                                 if(!project->isEmpty(fixedSubDep + ".file"))
2284                                     d = project->first(fixedSubDep + ".file");
2285                                 else if(!project->isEmpty(fixedSubDep + ".subdir"))
2286                                     d = project->first(fixedSubDep + ".subdir");
2287                                 st->depends += "sub-" + d.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2288                             }
2289                             found = true;
2290                             break;
2291                         }
2292                     }
2293                     if(!found) {
2294                         QString depend_str = depends.at(depend);
2295                         st->depends += depend_str.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2296                     }
2297                 }
2298             }
2299             if(!project->isEmpty(fixedSubdir + ".target")) {
2300                 st->target = project->first(fixedSubdir + ".target");
2301             } else {
2302                 st->target = "sub-" + file;
2303         st->target = st->target.replace(QRegExp("[^a-zA-Z0-9_]"),"-");
2304             }
2305         }
2306     }
2307     return targets;
2308 }
2309
2310 void
2311 MakefileGenerator::writeSubDirs(QTextStream &t)
2312 {
2313     QList<SubTarget*> targets = findSubDirsSubTargets();
2314     t << "first: make_first" << endl;
2315     int flags = SubTargetInstalls;
2316     if(project->isActiveConfig("ordered"))
2317         flags |= SubTargetOrdered;
2318     writeSubTargets(t, targets, flags);
2319     qDeleteAll(targets);
2320 }
2321
2322 void MakefileGenerator::writeSubMakeCall(QTextStream &t, const QString &callPrefix,
2323                                          const QString &makeArguments)
2324 {
2325     t << callPrefix << "$(MAKE)" << makeArguments << endl;
2326 }
2327
2328 void
2329 MakefileGenerator::writeSubTargetCall(QTextStream &t,
2330         const QString &in_directory, const QString &in, const QString &out_directory, const QString &out,
2331         const QString &out_directory_cdin, const QString &makefilein)
2332 {
2333     QString pfx;
2334     if (!in.isEmpty()) {
2335         if (!in_directory.isEmpty())
2336             t << "\n\t" << mkdir_p_asstring(out_directory);
2337         pfx = "( " + chkfile + " " + out + " " + chkglue
2338               + "$(QMAKE) " + in + buildArgs(in_directory) + " -o " + out
2339               + " ) && ";
2340     }
2341     writeSubMakeCall(t, out_directory_cdin + pfx, makefilein);
2342 }
2343
2344 void
2345 MakefileGenerator::writeSubTargets(QTextStream &t, QList<MakefileGenerator::SubTarget*> targets, int flags)
2346 {
2347     // blasted includes
2348     const QStringList &qeui = project->values("QMAKE_EXTRA_INCLUDES");
2349     for (QStringList::ConstIterator qeui_it = qeui.begin(); qeui_it != qeui.end(); ++qeui_it)
2350         t << "include " << (*qeui_it) << endl;
2351
2352     if (!(flags & SubTargetSkipDefaultVariables)) {
2353         QString ofile = Option::fixPathToTargetOS(Option::output.fileName());
2354         if(ofile.lastIndexOf(Option::dir_sep) != -1)
2355             ofile.remove(0, ofile.lastIndexOf(Option::dir_sep) +1);
2356         t << "MAKEFILE      = " << ofile << endl;
2357         /* Calling Option::fixPathToTargetOS() is necessary for MinGW/MSYS, which requires
2358          * back-slashes to be turned into slashes. */
2359         t << "QMAKE         = " << var("QMAKE_QMAKE") << endl;
2360         t << "DEL_FILE      = " << var("QMAKE_DEL_FILE") << endl;
2361         t << "CHK_DIR_EXISTS= " << var("QMAKE_CHK_DIR_EXISTS") << endl;
2362         t << "MKDIR         = " << var("QMAKE_MKDIR") << endl;
2363         t << "COPY          = " << var("QMAKE_COPY") << endl;
2364         t << "COPY_FILE     = " << var("QMAKE_COPY_FILE") << endl;
2365         t << "COPY_DIR      = " << var("QMAKE_COPY_DIR") << endl;
2366         t << "INSTALL_FILE  = " << var("QMAKE_INSTALL_FILE") << endl;
2367         t << "INSTALL_PROGRAM = " << var("QMAKE_INSTALL_PROGRAM") << endl;
2368         t << "INSTALL_DIR   = " << var("QMAKE_INSTALL_DIR") << endl;
2369         t << "DEL_FILE      = " << var("QMAKE_DEL_FILE") << endl;
2370         t << "SYMLINK       = " << var("QMAKE_SYMBOLIC_LINK") << endl;
2371         t << "DEL_DIR       = " << var("QMAKE_DEL_DIR") << endl;
2372         t << "MOVE          = " << var("QMAKE_MOVE") << endl;
2373         t << "SUBTARGETS    = ";     // subtargets are sub-directory
2374         for(int target = 0; target < targets.size(); ++target)
2375             t << " \\\n\t\t" << targets.at(target)->target;
2376         t << endl << endl;
2377     }
2378     writeExtraVariables(t);
2379
2380     QStringList targetSuffixes;
2381     const QString abs_source_path = project->first("QMAKE_ABSOLUTE_SOURCE_PATH");
2382     if (!(flags & SubTargetSkipDefaultTargets)) {
2383         targetSuffixes << "make_first" << "all" << "clean" << "distclean"
2384                        << QString((flags & SubTargetInstalls) ? "install_subtargets" : "install")
2385                        << QString((flags & SubTargetInstalls) ? "uninstall_subtargets" : "uninstall");
2386     }
2387
2388     bool dont_recurse = project->isActiveConfig("dont_recurse");
2389
2390     // generate target rules
2391     for(int target = 0; target < targets.size(); ++target) {
2392         SubTarget *subtarget = targets.at(target);
2393         QString in_directory = subtarget->in_directory;
2394         if(!in_directory.isEmpty() && !in_directory.endsWith(Option::dir_sep))
2395             in_directory += Option::dir_sep;
2396         QString out_directory = subtarget->out_directory;
2397         if(!out_directory.isEmpty() && !out_directory.endsWith(Option::dir_sep))
2398             out_directory += Option::dir_sep;
2399         if(!abs_source_path.isEmpty() && out_directory.startsWith(abs_source_path))
2400             out_directory = Option::output_dir + out_directory.mid(abs_source_path.length());
2401
2402         QString out_directory_cdin = out_directory.isEmpty() ? "\n\t"
2403                                                              : "\n\tcd " + out_directory + " && ";
2404         QString makefilein = " -f " + subtarget->makefile;
2405
2406         //qmake it
2407         QString out;
2408         QString in;
2409         if(!subtarget->profile.isEmpty()) {
2410             out = subtarget->makefile;
2411             in = escapeFilePath(fileFixify(in_directory + subtarget->profile, FileFixifyAbsolute));
2412             if(out.startsWith(in_directory))
2413                 out = out.mid(in_directory.length());
2414             t << subtarget->target << "-qmake_all: ";
2415             if (flags & SubTargetOrdered) {
2416                 if (target)
2417                     t << targets.at(target - 1)->target << "-qmake_all";
2418             } else {
2419                 if (!subtarget->depends.isEmpty())
2420                     t << valGlue(subtarget->depends, QString(), "-qmake_all ", "-qmake_all");
2421             }
2422             t << " FORCE\n\t";
2423             if(!in_directory.isEmpty()) {
2424                 t << mkdir_p_asstring(out_directory)
2425                   << out_directory_cdin;
2426             }
2427             t << "$(QMAKE) " << in << buildArgs(in_directory) << " -o " << out;
2428             if (!dont_recurse)
2429                 writeSubMakeCall(t, out_directory_cdin, makefilein + " qmake_all");
2430             else
2431                 t << endl;
2432         }
2433
2434         { //actually compile
2435             t << subtarget->target << ":";
2436             if(!subtarget->depends.isEmpty())
2437                 t << " " << valList(subtarget->depends);
2438             t << " FORCE";
2439             writeSubTargetCall(t, in_directory, in, out_directory, out,
2440                                out_directory_cdin, makefilein);
2441         }
2442
2443         for(int suffix = 0; suffix < targetSuffixes.size(); ++suffix) {
2444             QString s = targetSuffixes.at(suffix);
2445             if(s == "install_subtargets")
2446                 s = "install";
2447             else if(s == "uninstall_subtargets")
2448                 s = "uninstall";
2449             else if(s == "make_first")
2450                 s = QString();
2451
2452             if(flags & SubTargetOrdered) {
2453                 t << subtarget->target << "-" << targetSuffixes.at(suffix) << "-ordered:";
2454                 if(target)
2455                     t << " " << targets.at(target-1)->target << "-" << targetSuffixes.at(suffix) << "-ordered ";
2456                 t << " FORCE";
2457                 writeSubTargetCall(t, in_directory, in, out_directory, out,
2458                                    out_directory_cdin, makefilein + " " + s);
2459             }
2460             t << subtarget->target << "-" << targetSuffixes.at(suffix) << ":";
2461             if(!subtarget->depends.isEmpty())
2462                 t << " " << valGlue(subtarget->depends, QString(), "-" + targetSuffixes.at(suffix) + " ",
2463                                     "-"+targetSuffixes.at(suffix));
2464             t << " FORCE";
2465             writeSubTargetCall(t, in_directory, in, out_directory, out,
2466                                out_directory_cdin, makefilein + " " + s);
2467         }
2468     }
2469     t << endl;
2470
2471     if (!(flags & SubTargetSkipDefaultTargets)) {
2472         writeMakeQmake(t, true);
2473
2474         t << "qmake_all:";
2475         if(!targets.isEmpty()) {
2476             for(QList<SubTarget*>::Iterator it = targets.begin(); it != targets.end(); ++it) {
2477                 if(!(*it)->profile.isEmpty())
2478                     t << " " << (*it)->target << "-" << "qmake_all";
2479             }
2480         }
2481         t << " FORCE" << endl << endl;
2482     }
2483
2484     for(int s = 0; s < targetSuffixes.size(); ++s) {
2485         QString suffix = targetSuffixes.at(s);
2486         if(!(flags & SubTargetInstalls) && suffix.endsWith("install"))
2487             continue;
2488
2489         t << suffix << ":";
2490         for(int target = 0; target < targets.size(); ++target) {
2491             SubTarget *subTarget = targets.at(target);
2492             if (suffix == "make_first"
2493                 && project->values(subTarget->name + ".CONFIG").indexOf("no_default_target") != -1) {
2494                 continue;
2495             }
2496             if((suffix == "install_subtargets" || suffix == "uninstall_subtargets")
2497                 && project->values(subTarget->name + ".CONFIG").indexOf("no_default_install") != -1) {
2498                 continue;
2499             }
2500             QString targetRule = subTarget->target + "-" + suffix;
2501             if(flags & SubTargetOrdered)
2502                 targetRule += "-ordered";
2503             t << " " << targetRule;
2504         }
2505         if(suffix == "all" || suffix == "make_first")
2506             t << varGlue("ALL_DEPS"," "," ","");
2507         if(suffix == "clean")
2508             t << varGlue("CLEAN_DEPS"," "," ","");
2509         t << " FORCE" << endl;
2510         if(suffix == "clean") {
2511             t << fileVarGlue("QMAKE_CLEAN", "\t-$(DEL_FILE) ", "\n\t-$(DEL_FILE) ", "\n");
2512         } else if(suffix == "distclean") {
2513             QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
2514             if(!ofile.isEmpty())
2515                 t << "\t-$(DEL_FILE) " << ofile << endl;
2516             t << fileVarGlue("QMAKE_DISTCLEAN", "\t-$(DEL_FILE) ", " ", "\n");
2517         }
2518     }
2519
2520     // user defined targets
2521     const QStringList &qut = project->values("QMAKE_EXTRA_TARGETS");
2522     for (QStringList::ConstIterator qut_it = qut.begin(); qut_it != qut.end(); ++qut_it) {
2523         QString targ = var((*qut_it) + ".target"),
2524                  cmd = var((*qut_it) + ".commands"), deps;
2525         if(targ.isEmpty())
2526             targ = (*qut_it);
2527         t << endl;
2528
2529         const QStringList &deplist = project->values((*qut_it) + ".depends");
2530         for (QStringList::ConstIterator dep_it = deplist.begin(); dep_it != deplist.end(); ++dep_it) {
2531             QString dep = var((*dep_it) + ".target");
2532             if(dep.isEmpty())
2533                 dep = Option::fixPathToTargetOS(*dep_it, false);
2534             deps += " " + dep;
2535         }
2536         if(project->values((*qut_it) + ".CONFIG").indexOf("recursive") != -1) {
2537             QSet<QString> recurse;
2538             if(project->isSet((*qut_it) + ".recurse")) {
2539                 recurse = project->values((*qut_it) + ".recurse").toSet();
2540             } else {
2541                 for(int target = 0; target < targets.size(); ++target)
2542                     recurse.insert(targets.at(target)->name);
2543             }
2544             for(int target = 0; target < targets.size(); ++target) {
2545                 SubTarget *subtarget = targets.at(target);
2546                 QString in_directory = subtarget->in_directory;
2547                 if(!in_directory.isEmpty() && !in_directory.endsWith(Option::dir_sep))
2548                     in_directory += Option::dir_sep;
2549                 QString out_directory = subtarget->out_directory;
2550                 if(!out_directory.isEmpty() && !out_directory.endsWith(Option::dir_sep))
2551                     out_directory += Option::dir_sep;
2552                 if(!abs_source_path.isEmpty() && out_directory.startsWith(abs_source_path))
2553                     out_directory = Option::output_dir + out_directory.mid(abs_source_path.length());
2554
2555                 if(!recurse.contains(subtarget->name))
2556                     continue;
2557
2558                 QString out_directory_cdin = out_directory.isEmpty() ? "\n\t"
2559                                                                      : "\n\tcd " + out_directory + " && ";
2560                 QString makefilein = " -f " + subtarget->makefile;
2561
2562                 QString out;
2563                 QString in;
2564                 if (!subtarget->profile.isEmpty()) {
2565                     out = subtarget->makefile;
2566                     in = escapeFilePath(fileFixify(in_directory + subtarget->profile, FileFixifyAbsolute));
2567                     if (out.startsWith(in_directory))
2568                         out = out.mid(in_directory.length());
2569                 }
2570
2571                 //write the rule/depends
2572                 if(flags & SubTargetOrdered) {
2573                     const QString dep = subtarget->target + "-" + (*qut_it) + "_ordered";
2574                     t << dep << ":";
2575                     if(target)
2576                         t << " " << targets.at(target-1)->target << "-" << (*qut_it) << "_ordered ";
2577                     deps += " " + dep;
2578                 } else {
2579                     const QString dep = subtarget->target + "-" + (*qut_it);
2580                     t << dep << ":";
2581                     if(!subtarget->depends.isEmpty())
2582                         t << " " << valGlue(subtarget->depends, QString(), "-" + (*qut_it) + " ", "-" + (*qut_it));
2583                     deps += " " + dep;
2584                 }
2585
2586                 QString sub_targ = targ;
2587                 if(project->isSet((*qut_it) + ".recurse_target"))
2588                     sub_targ = project->first((*qut_it) + ".recurse_target");
2589
2590                 //write the commands
2591                 writeSubTargetCall(t, in_directory, in, out_directory, out,
2592                                    out_directory_cdin, makefilein + " " + sub_targ);
2593             }
2594         }
2595         if (project->values((*qut_it) + ".CONFIG").indexOf("phony") != -1)
2596             deps += " FORCE";
2597         t << targ << ":" << deps << "\n";
2598         if(!cmd.isEmpty())
2599             t << "\t" << cmd << endl;
2600     }
2601
2602     if(flags & SubTargetInstalls) {
2603         project->values("INSTALLDEPS")   += "install_subtargets";
2604         project->values("UNINSTALLDEPS") += "uninstall_subtargets";
2605         writeInstalls(t, "INSTALLS", true);
2606     }
2607     t << "FORCE:" << endl << endl;
2608 }
2609
2610 void
2611 MakefileGenerator::writeMakeQmake(QTextStream &t, bool noDummyQmakeAll)
2612 {
2613     QString ofile = Option::fixPathToTargetOS(fileFixify(Option::output.fileName()));
2614     if(project->isEmpty("QMAKE_FAILED_REQUIREMENTS") && !project->isEmpty("QMAKE_INTERNAL_PRL_FILE")) {
2615         QStringList files = fileFixify(Option::mkfile::project_files);
2616         t << escapeDependencyPath(project->first("QMAKE_INTERNAL_PRL_FILE")) << ": " << "\n\t"
2617           << "@$(QMAKE) -prl " << buildArgs() << " " << files.join(" ") << endl;
2618     }
2619
2620     QString pfile = project->projectFile();
2621     if(pfile != "(stdin)") {
2622         QString qmake = build_args();
2623         if(!ofile.isEmpty() && !project->isActiveConfig("no_autoqmake")) {
2624             t << escapeFilePath(ofile) << ": " << escapeDependencyPath(fileFixify(pfile)) << " ";
2625             if (Option::mkfile::do_cache) {
2626                 if (!project->confFile().isEmpty())
2627                     t <<  escapeDependencyPath(fileFixify(project->confFile())) << " ";
2628                 if (!project->cacheFile().isEmpty())
2629                     t <<  escapeDependencyPath(fileFixify(project->cacheFile())) << " ";
2630             }
2631             if(!specdir().isEmpty()) {
2632                 if(exists(Option::fixPathToLocalOS(specdir()+QDir::separator()+"qmake.conf")))
2633                     t << escapeDependencyPath(specdir() + Option::dir_sep + "qmake.conf") << " ";
2634             }
2635             const QStringList &included = project->values("QMAKE_INTERNAL_INCLUDED_FILES");
2636             t << escapeDependencyPaths(included).join(" \\\n\t\t") << "\n\t"
2637               << qmake << endl;
2638             for(int include = 0; include < included.size(); ++include) {
2639                 const QString i(included.at(include));
2640                 if(!i.isEmpty())
2641                     t << i << ":" << endl;
2642             }
2643         }
2644         if(project->first("QMAKE_ORIG_TARGET") != "qmake") {
2645             t << "qmake: FORCE\n\t@" << qmake << endl << endl;
2646             if (!noDummyQmakeAll)
2647                 t << "qmake_all: FORCE" << endl << endl;
2648         }
2649     }
2650 }
2651
2652 QFileInfo
2653 MakefileGenerator::fileInfo(QString file) const
2654 {
2655     static QHash<FileInfoCacheKey, QFileInfo> *cache = 0;
2656     static QFileInfo noInfo = QFileInfo();
2657     if(!cache) {
2658         cache = new QHash<FileInfoCacheKey, QFileInfo>;
2659         qmakeAddCacheClear(qmakeDeleteCacheClear<QHash<FileInfoCacheKey, QFileInfo> >, (void**)&cache);
2660     }
2661     FileInfoCacheKey cacheKey(file);
2662     QFileInfo value = cache->value(cacheKey, noInfo);
2663     if (value != noInfo)
2664         return value;
2665
2666     QFileInfo fi(file);
2667     if (fi.exists())
2668         cache->insert(cacheKey, fi);
2669     return fi;
2670 }
2671
2672 QString
2673 MakefileGenerator::unescapeFilePath(const QString &path) const
2674 {
2675     QString ret = path;
2676     if(!ret.isEmpty()) {
2677         if(ret.contains(QLatin1String("\\ ")))
2678             ret.replace(QLatin1String("\\ "), QLatin1String(" "));
2679         if(ret.contains(QLatin1Char('\"')))
2680             ret.remove(QLatin1Char('\"'));
2681     }
2682     return ret;
2683 }
2684
2685 QStringList
2686 MakefileGenerator::escapeFilePaths(const QStringList &paths) const
2687 {
2688     QStringList ret;
2689     for(int i = 0; i < paths.size(); ++i)
2690         ret.append(escapeFilePath(paths.at(i)));
2691     return ret;
2692 }
2693
2694 QStringList
2695 MakefileGenerator::escapeDependencyPaths(const QStringList &paths) const
2696 {
2697     QStringList ret;
2698     for(int i = 0; i < paths.size(); ++i)
2699         ret.append(escapeDependencyPath(paths.at(i)));
2700     return ret;
2701 }
2702
2703 QStringList
2704 MakefileGenerator::unescapeFilePaths(const QStringList &paths) const
2705 {
2706     QStringList ret;
2707     for(int i = 0; i < paths.size(); ++i)
2708         ret.append(unescapeFilePath(paths.at(i)));
2709     return ret;
2710 }
2711
2712 QStringList
2713 MakefileGenerator::fileFixify(const QStringList& files, const QString &out_dir, const QString &in_dir,
2714                               FileFixifyType fix, bool canon) const
2715 {
2716     if(files.isEmpty())
2717         return files;
2718     QStringList ret;
2719     for(QStringList::ConstIterator it = files.begin(); it != files.end(); ++it) {
2720         if(!(*it).isEmpty())
2721             ret << fileFixify((*it), out_dir, in_dir, fix, canon);
2722     }
2723     return ret;
2724 }
2725
2726 QString
2727 MakefileGenerator::fileFixify(const QString& file, const QString &out_d, const QString &in_d,
2728                               FileFixifyType fix, bool canon) const
2729 {
2730     if(file.isEmpty())
2731         return file;
2732     QString ret = unescapeFilePath(file);
2733
2734     //do the fixin'
2735     QString orig_file = ret;
2736     if(ret.startsWith(QLatin1Char('~'))) {
2737         if(ret.startsWith(QLatin1String("~/")))
2738             ret = QDir::homePath() + ret.mid(1);
2739         else
2740             warn_msg(WarnLogic, "Unable to expand ~ in %s", ret.toLatin1().constData());
2741     }
2742     if(fix == FileFixifyAbsolute || (fix == FileFixifyDefault && project->isActiveConfig("no_fixpath"))) {
2743         if(fix == FileFixifyAbsolute && QDir::isRelativePath(ret)) { //already absolute
2744             QString pwd = qmake_getpwd();
2745             if (!pwd.endsWith(QLatin1Char('/')))
2746                 pwd += QLatin1Char('/');
2747             ret.prepend(pwd);
2748         }
2749         ret = Option::fixPathToTargetOS(ret, false, canon);
2750     } else { //fix it..
2751         QString out_dir = QDir(Option::output_dir).absoluteFilePath(out_d);
2752         QString in_dir  = QDir(qmake_getpwd()).absoluteFilePath(in_d);
2753         {
2754             QFileInfo in_fi(fileInfo(in_dir));
2755             if(in_fi.exists())
2756                 in_dir = in_fi.canonicalFilePath();
2757             QFileInfo out_fi(fileInfo(out_dir));
2758             if(out_fi.exists())
2759                 out_dir = out_fi.canonicalFilePath();
2760         }
2761
2762         QString qfile(Option::fixPathToLocalOS(ret, true, canon));
2763         QFileInfo qfileinfo(fileInfo(qfile));
2764         if(out_dir != in_dir || !qfileinfo.isRelative()) {
2765             if(qfileinfo.isRelative()) {
2766                 ret = in_dir + "/" + qfile;
2767                 qfileinfo.setFile(ret);
2768             }
2769             ret = Option::fixPathToTargetOS(ret, false, canon);
2770             if(canon && qfileinfo.exists() &&
2771                file == Option::fixPathToTargetOS(ret, true, canon))
2772                 ret = Option::fixPathToTargetOS(qfileinfo.canonicalFilePath());
2773             QString match_dir = Option::fixPathToTargetOS(out_dir, false, canon);
2774             if(ret == match_dir) {
2775                 ret = "";
2776             } else if(ret.startsWith(match_dir + Option::dir_sep)) {
2777                 ret = ret.mid(match_dir.length() + Option::dir_sep.length());
2778             } else {
2779                 //figure out the depth
2780                 int depth = 4;
2781                 if(Option::qmake_mode == Option::QMAKE_GENERATE_MAKEFILE ||
2782                    Option::qmake_mode == Option::QMAKE_GENERATE_PRL) {
2783                     if(project && !project->isEmpty("QMAKE_PROJECT_DEPTH"))
2784                         depth = project->first("QMAKE_PROJECT_DEPTH").toInt();
2785                     else if(Option::mkfile::cachefile_depth != -1)
2786                         depth = Option::mkfile::cachefile_depth;
2787                 }
2788                 //calculate how much can be removed
2789                 QString dot_prefix;
2790                 for(int i = 1; i <= depth; i++) {
2791                     int sl = match_dir.lastIndexOf(Option::dir_sep);
2792                     if(sl == -1)
2793                         break;
2794                     match_dir = match_dir.left(sl);
2795                     if(match_dir.isEmpty())
2796                         break;
2797                     if(ret.startsWith(match_dir + Option::dir_sep)) {
2798                         //concat
2799                         int remlen = ret.length() - (match_dir.length() + 1);
2800                         if(remlen < 0)
2801                             remlen = 0;
2802                         ret = ret.right(remlen);
2803                         //prepend
2804                         for(int o = 0; o < i; o++)
2805                             dot_prefix += ".." + Option::dir_sep;
2806                         break;
2807                     }
2808                 }
2809                 ret.prepend(dot_prefix);
2810             }
2811         } else {
2812             ret = Option::fixPathToTargetOS(ret, false, canon);
2813         }
2814     }
2815     if(ret.isEmpty())
2816         ret = ".";
2817     debug_msg(3, "Fixed[%d,%d] %s :: to :: %s [%s::%s] [%s::%s]", fix, canon, orig_file.toLatin1().constData(),
2818               ret.toLatin1().constData(), in_d.toLatin1().constData(), out_d.toLatin1().constData(),
2819               qmake_getpwd().toLatin1().constData(), Option::output_dir.toLatin1().constData());
2820     return ret;
2821 }
2822
2823 void
2824 MakefileGenerator::checkMultipleDefinition(const QString &f, const QString &w)
2825 {
2826     if(!(Option::warn_level & WarnLogic))
2827         return;
2828     QString file = f;
2829     int slsh = f.lastIndexOf(Option::dir_sep);
2830     if(slsh != -1)
2831         file.remove(0, slsh + 1);
2832     const QStringList &l = project->values(w);
2833     for (QStringList::ConstIterator val_it = l.begin(); val_it != l.end(); ++val_it) {
2834         QString file2((*val_it));
2835         slsh = file2.lastIndexOf(Option::dir_sep);
2836         if(slsh != -1)
2837             file2.remove(0, slsh + 1);
2838         if(file2 == file) {
2839             warn_msg(WarnLogic, "Found potential symbol conflict of %s (%s) in %s",
2840                      file.toLatin1().constData(), (*val_it).toLatin1().constData(), w.toLatin1().constData());
2841             break;
2842         }
2843     }
2844 }
2845
2846 QMakeLocalFileName
2847 MakefileGenerator::fixPathForFile(const QMakeLocalFileName &file, bool forOpen)
2848 {
2849     if(forOpen)
2850         return QMakeLocalFileName(fileFixify(file.real(), qmake_getpwd(), Option::output_dir));
2851     return QMakeLocalFileName(fileFixify(file.real()));
2852 }
2853
2854 QFileInfo
2855 MakefileGenerator::findFileInfo(const QMakeLocalFileName &file)
2856 {
2857     return fileInfo(file.local());
2858 }
2859
2860 QMakeLocalFileName
2861 MakefileGenerator::findFileForDep(const QMakeLocalFileName &dep, const QMakeLocalFileName &file)
2862 {
2863     QMakeLocalFileName ret;
2864     if(!project->isEmpty("SKIP_DEPENDS")) {
2865         bool found = false;
2866         const QStringList &nodeplist = project->values("SKIP_DEPENDS");
2867         for (QStringList::ConstIterator it = nodeplist.begin();
2868             it != nodeplist.end(); ++it) {
2869             QRegExp regx((*it));
2870             if(regx.indexIn(dep.local()) != -1) {
2871                 found = true;
2872                 break;
2873             }
2874         }
2875         if(found)
2876             return ret;
2877     }
2878
2879     ret = QMakeSourceFileInfo::findFileForDep(dep, file);
2880     if(!ret.isNull())
2881         return ret;
2882
2883     //these are some "hacky" heuristics it will try to do on an include
2884     //however these can be turned off at runtime, I'm not sure how
2885     //reliable these will be, most likely when problems arise turn it off
2886     //and see if they go away..
2887     if(Option::mkfile::do_dep_heuristics) {
2888         if(depHeuristicsCache.contains(dep.real()))
2889             return depHeuristicsCache[dep.real()];
2890
2891         if(Option::output_dir != qmake_getpwd()
2892            && QDir::isRelativePath(dep.real())) { //is it from the shadow tree
2893             QList<QMakeLocalFileName> depdirs = QMakeSourceFileInfo::dependencyPaths();
2894             depdirs.prepend(fileInfo(file.real()).absoluteDir().path());
2895             QString pwd = qmake_getpwd();
2896             if(pwd.at(pwd.length()-1) != '/')
2897                 pwd += '/';
2898             for(int i = 0; i < depdirs.count(); i++) {
2899                 QString dir = depdirs.at(i).real();
2900                 if(!QDir::isRelativePath(dir) && dir.startsWith(pwd))
2901                     dir = dir.mid(pwd.length());
2902                 if(QDir::isRelativePath(dir)) {
2903                     if(!dir.endsWith(Option::dir_sep))
2904                         dir += Option::dir_sep;
2905                     QString shadow = fileFixify(dir + dep.local(), pwd, Option::output_dir);
2906                     if(exists(shadow)) {
2907                         ret = QMakeLocalFileName(shadow);
2908                         goto found_dep_from_heuristic;
2909                     }
2910                 }
2911             }
2912         }
2913         { //is it from an EXTRA_TARGET
2914             const QString dep_basename = dep.local().section(Option::dir_sep, -1);
2915             const QStringList &qut = project->values("QMAKE_EXTRA_TARGETS");
2916             for (QStringList::ConstIterator it = qut.begin(); it != qut.end(); ++it) {
2917                 QString targ = var((*it) + ".target");
2918                 if(targ.isEmpty())
2919                     targ = (*it);
2920                 QString out = Option::fixPathToTargetOS(targ);
2921                 if(out == dep.real() || out.section(Option::dir_sep, -1) == dep_basename) {
2922                     ret = QMakeLocalFileName(out);
2923                     goto found_dep_from_heuristic;
2924                 }
2925             }
2926         }
2927         { //is it from an EXTRA_COMPILER
2928             const QString dep_basename = dep.local().section(Option::dir_sep, -1);
2929             const QStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
2930             for(QStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
2931                 QString tmp_out = project->values((*it) + ".output").first();
2932                 if(tmp_out.isEmpty())
2933                     continue;
2934                 const QStringList &tmp = project->values((*it) + ".input");
2935                 for (QStringList::ConstIterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) {
2936                     const QStringList &inputs = project->values((*it2));
2937                     for (QStringList::ConstIterator input = inputs.begin(); input != inputs.end(); ++input) {
2938                         QString out = Option::fixPathToTargetOS(unescapeFilePath(replaceExtraCompilerVariables(tmp_out, (*input), QString())));
2939               if(out == dep.real() || out.section(Option::dir_sep, -1) == dep_basename) {
2940                             ret = QMakeLocalFileName(fileFixify(out, qmake_getpwd(), Option::output_dir));
2941                             goto found_dep_from_heuristic;
2942                         }
2943                     }
2944                 }
2945             }
2946         }
2947     found_dep_from_heuristic:
2948         depHeuristicsCache.insert(dep.real(), ret);
2949     }
2950     return ret;
2951 }
2952
2953 QStringList
2954 &MakefileGenerator::findDependencies(const QString &file)
2955 {
2956     const QString fixedFile = fileFixify(file);
2957     if(!dependsCache.contains(fixedFile)) {
2958 #if 1
2959         QStringList deps = QMakeSourceFileInfo::dependencies(file);
2960         if(file != fixedFile)
2961             deps += QMakeSourceFileInfo::dependencies(fixedFile);
2962 #else
2963         QStringList deps = QMakeSourceFileInfo::dependencies(fixedFile);
2964 #endif
2965         dependsCache.insert(fixedFile, deps);
2966     }
2967     return dependsCache[fixedFile];
2968 }
2969
2970 QString
2971 MakefileGenerator::specdir()
2972 {
2973     if (spec.isEmpty())
2974         spec = fileFixify(project->specDir());
2975     return spec;
2976 }
2977
2978 bool
2979 MakefileGenerator::openOutput(QFile &file, const QString &build) const
2980 {
2981     {
2982         QString outdir;
2983         if(!file.fileName().isEmpty()) {
2984             if(QDir::isRelativePath(file.fileName()))
2985                 file.setFileName(Option::output_dir + "/" + file.fileName()); //pwd when qmake was run
2986             QFileInfo fi(fileInfo(file.fileName()));
2987             if(fi.isDir())
2988                 outdir = file.fileName() + '/';
2989         }
2990         if(!outdir.isEmpty() || file.fileName().isEmpty()) {
2991             QString fname = "Makefile";
2992             if(!project->isEmpty("MAKEFILE"))
2993                fname = project->first("MAKEFILE");
2994             file.setFileName(outdir + fname);
2995         }
2996     }
2997     if(QDir::isRelativePath(file.fileName())) {
2998         QString fname = Option::output_dir;  //pwd when qmake was run
2999         if(!fname.endsWith("/"))
3000             fname += "/";
3001         fname += file.fileName();
3002         file.setFileName(fname);
3003     }
3004     if(!build.isEmpty())
3005         file.setFileName(file.fileName() + "." + build);
3006     if(project->isEmpty("QMAKE_MAKEFILE"))
3007         project->values("QMAKE_MAKEFILE").append(file.fileName());
3008     int slsh = file.fileName().lastIndexOf('/');
3009     if(slsh != -1)
3010         mkdir(file.fileName().left(slsh));
3011     if(file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
3012         QFileInfo fi(fileInfo(Option::output.fileName()));
3013         QString od;
3014         if(fi.isSymLink())
3015             od = fileInfo(fi.readLink()).absolutePath();
3016         else
3017             od = fi.path();
3018         od = QDir::fromNativeSeparators(od);
3019         if(QDir::isRelativePath(od)) {
3020             QString dir = Option::output_dir;
3021             if (!dir.endsWith('/') && !od.isEmpty())
3022                 dir += '/';
3023             od.prepend(dir);
3024         }
3025         Option::output_dir = od;
3026         return true;
3027     }
3028     return false;
3029 }
3030
3031 QString
3032 MakefileGenerator::pkgConfigFileName(bool fixify)
3033 {
3034     QString ret = var("TARGET");
3035     int slsh = ret.lastIndexOf(Option::dir_sep);
3036     if(slsh != -1)
3037         ret = ret.right(ret.length() - slsh - 1);
3038     if(ret.startsWith("lib"))
3039         ret = ret.mid(3);
3040     int dot = ret.indexOf('.');
3041     if(dot != -1)
3042         ret = ret.left(dot);
3043     ret += Option::pkgcfg_ext;
3044     QString subdir = project->first("QMAKE_PKGCONFIG_DESTDIR");
3045     if(!subdir.isEmpty()) {
3046         // initOutPaths() appends dir_sep, but just to be safe..
3047         if (!subdir.endsWith(Option::dir_sep))
3048             ret.prepend(Option::dir_sep);
3049         ret.prepend(subdir);
3050     }
3051     if(fixify) {
3052         if(QDir::isRelativePath(ret) && !project->isEmpty("DESTDIR"))
3053             ret.prepend(project->first("DESTDIR"));
3054         ret = Option::fixPathToLocalOS(fileFixify(ret, qmake_getpwd(), Option::output_dir));
3055     }
3056     return ret;
3057 }
3058
3059 QString
3060 MakefileGenerator::pkgConfigPrefix() const
3061 {
3062     if(!project->isEmpty("QMAKE_PKGCONFIG_PREFIX"))
3063         return project->first("QMAKE_PKGCONFIG_PREFIX");
3064     return QLibraryInfo::rawLocation(QLibraryInfo::PrefixPath, QLibraryInfo::FinalPaths);
3065 }
3066
3067 QString
3068 MakefileGenerator::pkgConfigFixPath(QString path) const
3069 {
3070     QString prefix = pkgConfigPrefix();
3071     if(path.startsWith(prefix))
3072         path = path.replace(prefix, "${prefix}");
3073     return path;
3074 }
3075
3076 void
3077 MakefileGenerator::writePkgConfigFile()
3078 {
3079     QString fname = pkgConfigFileName(), lname = fname;
3080     mkdir(fileInfo(fname).path());
3081     int slsh = lname.lastIndexOf(Option::dir_sep);
3082     if(slsh != -1)
3083         lname = lname.right(lname.length() - slsh - 1);
3084     QFile ft(fname);
3085     if(!ft.open(QIODevice::WriteOnly))
3086         return;
3087     project->values("ALL_DEPS").append(fileFixify(fname));
3088     QTextStream t(&ft);
3089
3090     QString prefix = pkgConfigPrefix();
3091     QString libDir = project->first("QMAKE_PKGCONFIG_LIBDIR");
3092     if(libDir.isEmpty())
3093         libDir = prefix + Option::dir_sep + "lib" + Option::dir_sep;
3094     QString includeDir = project->first("QMAKE_PKGCONFIG_INCDIR");
3095     if(includeDir.isEmpty())
3096         includeDir = prefix + "/include";
3097
3098     t << "prefix=" << prefix << endl;
3099     t << "exec_prefix=${prefix}\n"
3100       << "libdir=" << pkgConfigFixPath(libDir) << "\n"
3101       << "includedir=" << pkgConfigFixPath(includeDir) << endl;
3102     t << endl;
3103
3104     //extra PKGCONFIG variables
3105     const QStringList &pkgconfig_vars = project->values("QMAKE_PKGCONFIG_VARIABLES");
3106     for(int i = 0; i < pkgconfig_vars.size(); ++i) {
3107         QString var = project->first(pkgconfig_vars.at(i) + ".name"),
3108                 val = project->values(pkgconfig_vars.at(i) + ".value").join(" ");
3109         if(var.isEmpty())
3110             continue;
3111         if(val.isEmpty()) {
3112             const QStringList &var_vars = project->values(pkgconfig_vars.at(i) + ".variable");
3113             for(int v = 0; v < var_vars.size(); ++v) {
3114                 const QStringList &vars = project->values(var_vars.at(v));
3115                 for(int var = 0; var < vars.size(); ++var) {
3116                     if(!val.isEmpty())
3117                         val += " ";
3118                     val += pkgConfigFixPath(vars.at(var));
3119                 }
3120             }
3121         }
3122         t << var << "=" << val << endl;
3123     }
3124
3125     t << endl;
3126
3127     QString name = project->first("QMAKE_PKGCONFIG_NAME");
3128     if(name.isEmpty()) {
3129         name = project->first("QMAKE_ORIG_TARGET").toLower();
3130         name.replace(0, 1, name[0].toUpper());
3131     }
3132     t << "Name: " << name << endl;
3133     QString desc = project->values("QMAKE_PKGCONFIG_DESCRIPTION").join(" ");
3134     if(desc.isEmpty()) {
3135         if(name.isEmpty()) {
3136             desc = project->first("QMAKE_ORIG_TARGET").toLower();
3137             desc.replace(0, 1, desc[0].toUpper());
3138         } else {
3139             desc = name;
3140         }
3141         if(project->first("TEMPLATE") == "lib") {
3142             if(project->isActiveConfig("plugin"))
3143                desc += " Plugin";
3144             else
3145                desc += " Library";
3146         } else if(project->first("TEMPLATE") == "app") {
3147             desc += " Application";
3148         }
3149     }
3150     t << "Description: " << desc << endl;
3151     t << "Version: " << project->first("VERSION") << endl;
3152
3153     // libs
3154     t << "Libs: ";
3155     QString pkgConfiglibDir;
3156     QString pkgConfiglibName;
3157     if (target_mode == TARG_MACX_MODE && project->isActiveConfig("lib_bundle")) {
3158         pkgConfiglibDir = "-F${libdir}";
3159         QString bundle;
3160         if (!project->isEmpty("QMAKE_FRAMEWORK_BUNDLE_NAME"))
3161             bundle = unescapeFilePath(project->first("QMAKE_FRAMEWORK_BUNDLE_NAME"));
3162         else
3163             bundle = unescapeFilePath(project->first("TARGET"));
3164         int suffix = bundle.lastIndexOf(".framework");
3165         if (suffix != -1)
3166             bundle = bundle.left(suffix);
3167         pkgConfiglibName = "-framework " + bundle + " ";
3168     } else {
3169         pkgConfiglibDir = "-L${libdir}";
3170         pkgConfiglibName = "-l" + lname.left(lname.length()-Option::libtool_ext.length());
3171         if (project->isActiveConfig("shared"))
3172             pkgConfiglibName += project->first("TARGET_VERSION_EXT");
3173     }
3174     t << pkgConfiglibDir << " " << pkgConfiglibName << " " << endl;
3175
3176     QStringList libs;
3177     if(!project->isEmpty("QMAKE_INTERNAL_PRL_LIBS")) {
3178         libs = project->values("QMAKE_INTERNAL_PRL_LIBS");
3179     } else {
3180         libs << "QMAKE_LIBS"; //obvious one
3181     }
3182     libs << "QMAKE_LIBS_PRIVATE";
3183     libs << "QMAKE_LFLAGS_THREAD"; //not sure about this one, but what about things like -pthread?
3184     t << "Libs.private: ";
3185     for(QStringList::ConstIterator it = libs.begin(); it != libs.end(); ++it) {
3186         t << project->values((*it)).join(" ") << " ";
3187     }
3188     t << endl;
3189
3190     // flags
3191     // ### too many
3192     t << "Cflags: "
3193         // << var("QMAKE_CXXFLAGS") << " "
3194       << varGlue("PRL_EXPORT_DEFINES","-D"," -D"," ")
3195       << project->values("PRL_EXPORT_CXXFLAGS").join(" ")
3196       << project->values("QMAKE_PKGCONFIG_CFLAGS").join(" ")
3197         //      << varGlue("DEFINES","-D"," -D"," ")
3198       << " -I${includedir}" << endl;
3199
3200     // requires
3201     const QString requires = project->values("QMAKE_PKGCONFIG_REQUIRES").join(" ");
3202     if (!requires.isEmpty()) {
3203         t << "Requires: " << requires << endl;
3204     }
3205
3206     t << endl;
3207 }
3208
3209 QT_END_NAMESPACE