1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the qmake application of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:GPL-EXCEPT$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
21 ** included in the packaging of this file. Please review the following
22 ** information to ensure the GNU General Public License requirements will
23 ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
24 **
25 ** $QT_END_LICENSE$
26 **
27 ****************************************************************************/
28 
29 #include "winmakefile.h"
30 #include "option.h"
31 #include "project.h"
32 #include "meta.h"
33 #include <qtextstream.h>
34 #include <qstring.h>
35 #include <qhash.h>
36 #include <qregexp.h>
37 #include <qstringlist.h>
38 #include <qdir.h>
39 #include <stdlib.h>
40 
41 #include <algorithm>
42 
43 QT_BEGIN_NAMESPACE
44 
fixLibFlag(const ProString & lib)45 ProString Win32MakefileGenerator::fixLibFlag(const ProString &lib)
46 {
47     if (lib.startsWith("-l"))  // Fallback for unresolved -l libs.
48         return escapeFilePath(lib.mid(2) + QLatin1String(".lib"));
49     if (lib.startsWith("-L"))  // Lib search path. Needed only by -l above.
50         return QLatin1String("/LIBPATH:")
51                 + escapeFilePath(Option::fixPathToTargetOS(lib.mid(2).toQString(), false));
52     return escapeFilePath(Option::fixPathToTargetOS(lib.toQString(), false));
53 }
54 
55 MakefileGenerator::LibFlagType
parseLibFlag(const ProString & flag,ProString * arg)56 Win32MakefileGenerator::parseLibFlag(const ProString &flag, ProString *arg)
57 {
58     LibFlagType ret = MakefileGenerator::parseLibFlag(flag, arg);
59     if (ret != LibFlagFile)
60         return ret;
61     // MSVC compatibility. This should be deprecated.
62     if (flag.startsWith("/LIBPATH:")) {
63         *arg = flag.mid(9);
64         return LibFlagPath;
65     }
66     // These are pure qmake inventions. They *really* should be deprecated.
67     if (flag.startsWith("/L")) {
68         *arg = flag.mid(2);
69         return LibFlagPath;
70     }
71     if (flag.startsWith("/l")) {
72         *arg = flag.mid(2);
73         return LibFlagLib;
74     }
75     return LibFlagFile;
76 }
77 
78 class LibrarySearchPath : public QMakeLocalFileName
79 {
80 public:
81     LibrarySearchPath() = default;
82 
LibrarySearchPath(const QString & s)83     LibrarySearchPath(const QString &s)
84         : QMakeLocalFileName(s)
85     {
86     }
87 
LibrarySearchPath(QString && s,bool isDefault=false)88     LibrarySearchPath(QString &&s, bool isDefault = false)
89         : QMakeLocalFileName(std::move(s)), _default(isDefault)
90     {
91     }
92 
isDefault() const93     bool isDefault() const { return _default; }
94 
95 private:
96     bool _default = false;
97 };
98 
99 bool
findLibraries(bool linkPrl,bool mergeLflags)100 Win32MakefileGenerator::findLibraries(bool linkPrl, bool mergeLflags)
101 {
102     ProStringList impexts = project->values("QMAKE_LIB_EXTENSIONS");
103     if (impexts.isEmpty())
104         impexts = project->values("QMAKE_EXTENSION_STATICLIB");
105     QVector<LibrarySearchPath> dirs;
106     int libidx = 0;
107     for (const ProString &dlib : project->values("QMAKE_DEFAULT_LIBDIRS"))
108         dirs.append(LibrarySearchPath(dlib.toQString(), true));
109   static const char * const lflags[] = { "LIBS", "LIBS_PRIVATE",
110                                          "QMAKE_LIBS", "QMAKE_LIBS_PRIVATE", nullptr };
111   for (int i = 0; lflags[i]; i++) {
112     ProStringList &l = project->values(lflags[i]);
113     for (ProStringList::Iterator it = l.begin(); it != l.end();) {
114         const ProString &opt = *it;
115         ProString arg;
116         LibFlagType type = parseLibFlag(opt, &arg);
117         if (type == LibFlagPath) {
118             const QString argqstr = arg.toQString();
119             auto dit = std::find_if(dirs.cbegin(), dirs.cend(),
120                                  [&argqstr](const LibrarySearchPath &p)
121                                  {
122                                      return p.real() == argqstr;
123                                  });
124             int idx = dit == dirs.cend()
125                     ? -1
126                     : std::distance(dirs.cbegin(), dit);
127             if (idx >= 0 && idx < libidx) {
128                 it = l.erase(it);
129                 continue;
130             }
131             const LibrarySearchPath lp(argqstr);
132             dirs.insert(libidx++, lp);
133             (*it) = "-L" + lp.real();
134         } else if (type == LibFlagLib) {
135             QString lib = arg.toQString();
136             ProString verovr =
137                     project->first(ProKey("QMAKE_" + lib.toUpper() + "_VERSION_OVERRIDE"));
138             for (auto dir_it = dirs.begin(); dir_it != dirs.end(); ++dir_it) {
139                 QString cand = (*dir_it).real() + Option::dir_sep + lib;
140                 if (linkPrl && processPrlFile(cand, true)) {
141                     (*it) = cand;
142                     goto found;
143                 }
144                 QString libBase = (*dir_it).local() + '/' + lib + verovr;
145                 for (ProStringList::ConstIterator extit = impexts.cbegin();
146                      extit != impexts.cend(); ++extit) {
147                     if (exists(libBase + '.' + *extit)) {
148                         *it = (dir_it->isDefault() ? lib : cand)
149                                 + verovr + '.' + *extit;
150                         goto found;
151                     }
152                 }
153             }
154             // We assume if it never finds it that it's correct
155           found: ;
156         } else if (linkPrl && type == LibFlagFile) {
157             QString lib = opt.toQString();
158             if (fileInfo(lib).isAbsolute()) {
159                 if (processPrlFile(lib, false))
160                     (*it) = lib;
161             } else {
162                 for (auto dir_it = dirs.begin(); dir_it != dirs.end(); ++dir_it) {
163                     QString cand = (*dir_it).real() + Option::dir_sep + lib;
164                     if (processPrlFile(cand, false)) {
165                         (*it) = cand;
166                         break;
167                     }
168                 }
169             }
170         }
171 
172         ProStringList &prl_libs = project->values("QMAKE_CURRENT_PRL_LIBS");
173         for (int prl = 0; prl < prl_libs.size(); ++prl)
174             it = l.insert(++it, prl_libs.at(prl));
175         prl_libs.clear();
176         ++it;
177     }
178     if (mergeLflags) {
179         ProStringList lopts;
180         for (int lit = 0; lit < l.size(); ++lit) {
181             ProString opt = l.at(lit);
182             if (opt.startsWith(QLatin1String("-L"))) {
183                 if (!lopts.contains(opt))
184                     lopts.append(opt);
185             } else {
186                 // Make sure we keep the dependency order of libraries
187                 lopts.removeAll(opt);
188                 lopts.append(opt);
189             }
190         }
191         l = lopts;
192     }
193   }
194     return true;
195 }
196 
processPrlFileBase(QString & origFile,const QStringRef & origName,const QStringRef & fixedBase,int slashOff)197 bool Win32MakefileGenerator::processPrlFileBase(QString &origFile, const QStringRef &origName,
198                                                 const QStringRef &fixedBase, int slashOff)
199 {
200     if (MakefileGenerator::processPrlFileBase(origFile, origName, fixedBase, slashOff))
201         return true;
202     for (int off = fixedBase.length(); off > slashOff; off--) {
203         if (!fixedBase.at(off - 1).isDigit()) {
204             if (off != fixedBase.length()) {
205                 return MakefileGenerator::processPrlFileBase(
206                             origFile, origName, fixedBase.left(off), slashOff);
207             }
208             break;
209         }
210     }
211     return false;
212 }
213 
processVars()214 void Win32MakefileGenerator::processVars()
215 {
216     if (project->first("TEMPLATE").endsWith("aux"))
217         return;
218 
219     project->values("PRL_TARGET") =
220             project->values("QMAKE_ORIG_TARGET") = project->values("TARGET");
221     if (project->isEmpty("QMAKE_PROJECT_NAME"))
222         project->values("QMAKE_PROJECT_NAME") = project->values("QMAKE_ORIG_TARGET");
223     else if (project->first("TEMPLATE").startsWith("vc"))
224         project->values("MAKEFILE") = project->values("QMAKE_PROJECT_NAME");
225 
226     project->values("QMAKE_INCDIR") += project->values("QMAKE_INCDIR_POST");
227     project->values("QMAKE_LIBDIR") += project->values("QMAKE_LIBDIR_POST");
228 
229     if (!project->values("QMAKE_INCDIR").isEmpty())
230         project->values("INCLUDEPATH") += project->values("QMAKE_INCDIR");
231 
232     if (!project->values("VERSION").isEmpty()) {
233         QStringList l = project->first("VERSION").toQString().split('.');
234         if (l.size() > 0)
235             project->values("VER_MAJ").append(l[0]);
236         if (l.size() > 1)
237             project->values("VER_MIN").append(l[1]);
238     }
239 
240     // TARGET_VERSION_EXT will be used to add a version number onto the target name
241     if (!project->isActiveConfig("skip_target_version_ext")
242         && project->values("TARGET_VERSION_EXT").isEmpty()
243         && !project->values("VER_MAJ").isEmpty())
244         project->values("TARGET_VERSION_EXT").append(project->first("VER_MAJ"));
245 
246     fixTargetExt();
247     processRcFileVar();
248 
249     ProStringList libs;
250     ProStringList &libDir = project->values("QMAKE_LIBDIR");
251     for (ProStringList::Iterator libDir_it = libDir.begin(); libDir_it != libDir.end(); ++libDir_it) {
252         QString lib = (*libDir_it).toQString();
253         if (!lib.isEmpty()) {
254             if (lib.endsWith('\\'))
255                 lib.chop(1);
256             libs << QLatin1String("-L") + lib;
257         }
258     }
259     ProStringList &qmklibs = project->values("LIBS");
260     qmklibs = libs + qmklibs;
261 
262     if (project->values("TEMPLATE").contains("app")) {
263         project->values("QMAKE_CFLAGS") += project->values("QMAKE_CFLAGS_APP");
264         project->values("QMAKE_CXXFLAGS") += project->values("QMAKE_CXXFLAGS_APP");
265         project->values("QMAKE_LFLAGS") += project->values("QMAKE_LFLAGS_APP");
266     } else if (project->values("TEMPLATE").contains("lib") && project->isActiveConfig("dll")) {
267         if(!project->isActiveConfig("plugin") || !project->isActiveConfig("plugin_no_share_shlib_cflags")) {
268             project->values("QMAKE_CFLAGS") += project->values("QMAKE_CFLAGS_SHLIB");
269             project->values("QMAKE_CXXFLAGS") += project->values("QMAKE_CXXFLAGS_SHLIB");
270         }
271         if (project->isActiveConfig("plugin")) {
272             project->values("QMAKE_CFLAGS") += project->values("QMAKE_CFLAGS_PLUGIN");
273             project->values("QMAKE_CXXFLAGS") += project->values("QMAKE_CXXFLAGS_PLUGIN");
274             project->values("QMAKE_LFLAGS") += project->values("QMAKE_LFLAGS_PLUGIN");
275         } else {
276             project->values("QMAKE_LFLAGS") += project->values("QMAKE_LFLAGS_SHLIB");
277         }
278     }
279 }
280 
fixTargetExt()281 void Win32MakefileGenerator::fixTargetExt()
282 {
283     if (!project->values("QMAKE_APP_FLAG").isEmpty()) {
284         project->values("TARGET_EXT").append(".exe");
285     } else if (project->isActiveConfig("shared")) {
286         project->values("LIB_TARGET").prepend(project->first("QMAKE_PREFIX_STATICLIB")
287                                               + project->first("TARGET") + project->first("TARGET_VERSION_EXT")
288                                               + '.' + project->first("QMAKE_EXTENSION_STATICLIB"));
289         project->values("TARGET_EXT").append(project->first("TARGET_VERSION_EXT") + "."
290                 + project->first("QMAKE_EXTENSION_SHLIB"));
291         project->values("TARGET").first() = project->first("QMAKE_PREFIX_SHLIB") + project->first("TARGET");
292     } else {
293         project->values("TARGET_EXT").append("." + project->first("QMAKE_EXTENSION_STATICLIB"));
294         project->values("TARGET").first() = project->first("QMAKE_PREFIX_STATICLIB") + project->first("TARGET");
295         project->values("LIB_TARGET").prepend(project->first("TARGET") + project->first("TARGET_EXT"));  // for the .prl only
296     }
297 }
298 
processRcFileVar()299 void Win32MakefileGenerator::processRcFileVar()
300 {
301     if (Option::qmake_mode == Option::QMAKE_GENERATE_NOTHING)
302         return;
303 
304     const QString manifestFile = project->first("QMAKE_MANIFEST").toQString();
305     if (((!project->values("VERSION").isEmpty() || !project->values("RC_ICONS").isEmpty() || !manifestFile.isEmpty())
306         && project->values("RC_FILE").isEmpty()
307         && project->values("RES_FILE").isEmpty()
308         && !project->isActiveConfig("no_generated_target_info")
309         && (project->isActiveConfig("shared") || !project->values("QMAKE_APP_FLAG").isEmpty()))
310         || !project->values("QMAKE_WRITE_DEFAULT_RC").isEmpty()){
311 
312         QByteArray rcString;
313         QTextStream ts(&rcString, QFile::WriteOnly);
314 
315         QStringList vers = project->first("VERSION").toQString().split(".", Qt::SkipEmptyParts);
316         for (int i = vers.size(); i < 4; i++)
317             vers += "0";
318         QString versionString = vers.join('.');
319 
320         QStringList rcIcons;
321         const auto icons = project->values("RC_ICONS");
322         rcIcons.reserve(icons.size());
323         for (const ProString &icon : icons)
324             rcIcons.append(fileFixify(icon.toQString(), FileFixifyAbsolute));
325 
326         QString companyName;
327         if (!project->values("QMAKE_TARGET_COMPANY").isEmpty())
328             companyName = project->values("QMAKE_TARGET_COMPANY").join(' ');
329 
330         QString description;
331         if (!project->values("QMAKE_TARGET_DESCRIPTION").isEmpty())
332             description = project->values("QMAKE_TARGET_DESCRIPTION").join(' ');
333 
334         QString copyright;
335         if (!project->values("QMAKE_TARGET_COPYRIGHT").isEmpty())
336             copyright = project->values("QMAKE_TARGET_COPYRIGHT").join(' ');
337 
338         QString productName;
339         if (!project->values("QMAKE_TARGET_PRODUCT").isEmpty())
340             productName = project->values("QMAKE_TARGET_PRODUCT").join(' ');
341         else
342             productName = project->first("TARGET").toQString();
343 
344         QString originalName = project->first("TARGET") + project->first("TARGET_EXT");
345         int rcLang = project->intValue("RC_LANG", 1033);            // default: English(USA)
346         int rcCodePage = project->intValue("RC_CODEPAGE", 1200);    // default: Unicode
347 
348         ts << "#include <windows.h>\n";
349         ts << Qt::endl;
350         if (!rcIcons.isEmpty()) {
351             for (int i = 0; i < rcIcons.size(); ++i)
352                 ts << QString("IDI_ICON%1\tICON\tDISCARDABLE\t%2").arg(i + 1).arg(cQuoted(rcIcons[i])) << Qt::endl;
353             ts << Qt::endl;
354         }
355         if (!manifestFile.isEmpty()) {
356             QString manifestResourceId;
357             if (project->first("TEMPLATE") == "lib")
358                 manifestResourceId = QStringLiteral("ISOLATIONAWARE_MANIFEST_RESOURCE_ID");
359             else
360                 manifestResourceId = QStringLiteral("CREATEPROCESS_MANIFEST_RESOURCE_ID");
361             ts << manifestResourceId << " RT_MANIFEST \"" << manifestFile << "\"\n";
362         }
363         ts << "VS_VERSION_INFO VERSIONINFO\n";
364         ts << "\tFILEVERSION " << QString(versionString).replace(".", ",") << Qt::endl;
365         ts << "\tPRODUCTVERSION " << QString(versionString).replace(".", ",") << Qt::endl;
366         ts << "\tFILEFLAGSMASK 0x3fL\n";
367         ts << "#ifdef _DEBUG\n";
368         ts << "\tFILEFLAGS VS_FF_DEBUG\n";
369         ts << "#else\n";
370         ts << "\tFILEFLAGS 0x0L\n";
371         ts << "#endif\n";
372         ts << "\tFILEOS VOS__WINDOWS32\n";
373         if (project->isActiveConfig("shared"))
374             ts << "\tFILETYPE VFT_DLL\n";
375         else
376             ts << "\tFILETYPE VFT_APP\n";
377         ts << "\tFILESUBTYPE 0x0L\n";
378         ts << "\tBEGIN\n";
379         ts << "\t\tBLOCK \"StringFileInfo\"\n";
380         ts << "\t\tBEGIN\n";
381         ts << "\t\t\tBLOCK \""
382            << QString("%1%2").arg(rcLang, 4, 16, QLatin1Char('0')).arg(rcCodePage, 4, 16, QLatin1Char('0'))
383            << "\"\n";
384         ts << "\t\t\tBEGIN\n";
385         ts << "\t\t\t\tVALUE \"CompanyName\", \"" << companyName << "\\0\"\n";
386         ts << "\t\t\t\tVALUE \"FileDescription\", \"" <<  description << "\\0\"\n";
387         ts << "\t\t\t\tVALUE \"FileVersion\", \"" << versionString << "\\0\"\n";
388         ts << "\t\t\t\tVALUE \"LegalCopyright\", \"" << copyright << "\\0\"\n";
389         ts << "\t\t\t\tVALUE \"OriginalFilename\", \"" << originalName << "\\0\"\n";
390         ts << "\t\t\t\tVALUE \"ProductName\", \"" << productName << "\\0\"\n";
391         ts << "\t\t\t\tVALUE \"ProductVersion\", \"" << versionString << "\\0\"\n";
392         ts << "\t\t\tEND\n";
393         ts << "\t\tEND\n";
394         ts << "\t\tBLOCK \"VarFileInfo\"\n";
395         ts << "\t\tBEGIN\n";
396         ts << "\t\t\tVALUE \"Translation\", "
397            << QString("0x%1").arg(rcLang, 4, 16, QLatin1Char('0'))
398            << ", " << QString("%1").arg(rcCodePage, 4) << Qt::endl;
399         ts << "\t\tEND\n";
400         ts << "\tEND\n";
401         ts << "/* End of Version info */\n";
402         ts << Qt::endl;
403 
404         ts.flush();
405 
406 
407         QString rcFilename = project->first("OUT_PWD")
408                            + "/"
409                            + project->first("TARGET")
410                            + "_resource"
411                            + ".rc";
412         QFile rcFile(QDir::cleanPath(rcFilename));
413 
414         bool writeRcFile = true;
415         if (rcFile.exists() && rcFile.open(QFile::ReadOnly)) {
416             writeRcFile = rcFile.readAll() != rcString;
417             rcFile.close();
418         }
419         if (writeRcFile) {
420             bool ok;
421             ok = rcFile.open(QFile::WriteOnly);
422             if (!ok) {
423                 // The file can't be opened... try creating the containing
424                 // directory first (needed for clean shadow builds)
425                 QDir().mkpath(QFileInfo(rcFile).path());
426                 ok = rcFile.open(QFile::WriteOnly);
427             }
428             if (!ok) {
429                 ::fprintf(stderr, "Cannot open for writing: %s", rcFile.fileName().toLatin1().constData());
430                 ::exit(1);
431             }
432             rcFile.write(rcString);
433             rcFile.close();
434         }
435         if (project->values("QMAKE_WRITE_DEFAULT_RC").isEmpty())
436             project->values("RC_FILE").insert(0, rcFile.fileName());
437     }
438     if (!project->values("RC_FILE").isEmpty()) {
439         if (!project->values("RES_FILE").isEmpty()) {
440             fprintf(stderr, "Both rc and res file specified.\n");
441             fprintf(stderr, "Please specify one of them, not both.");
442             exit(1);
443         }
444         QString resFile = project->first("RC_FILE").toQString();
445 
446         // if this is a shadow build then use the absolute path of the rc file
447         if (Option::output_dir != qmake_getpwd()) {
448             QFileInfo fi(resFile);
449             project->values("RC_FILE").first() = fi.absoluteFilePath();
450         }
451 
452         resFile.replace(QLatin1String(".rc"), Option::res_ext);
453         project->values("RES_FILE").prepend(fileInfo(resFile).fileName());
454         QString resDestDir;
455         if (project->isActiveConfig("staticlib"))
456             resDestDir = project->first("DESTDIR").toQString();
457         else
458             resDestDir = project->first("OBJECTS_DIR").toQString();
459         if (!resDestDir.isEmpty()) {
460             resDestDir.append(Option::dir_sep);
461             project->values("RES_FILE").first().prepend(resDestDir);
462         }
463         project->values("RES_FILE").first() = Option::fixPathToTargetOS(
464                     project->first("RES_FILE").toQString(), false);
465         project->values("POST_TARGETDEPS") += project->values("RES_FILE");
466         project->values("CLEAN_FILES") += project->values("RES_FILE");
467     }
468 }
469 
writeCleanParts(QTextStream & t)470 void Win32MakefileGenerator::writeCleanParts(QTextStream &t)
471 {
472     t << "clean: compiler_clean " << depVar("CLEAN_DEPS");
473     {
474         const char *clean_targets[] = { "OBJECTS", "QMAKE_CLEAN", "CLEAN_FILES", nullptr };
475         for(int i = 0; clean_targets[i]; ++i) {
476             const ProStringList &list = project->values(clean_targets[i]);
477             const QString del_statement("-$(DEL_FILE)");
478             if(project->isActiveConfig("no_delete_multiple_files")) {
479                 for (ProStringList::ConstIterator it = list.begin(); it != list.end(); ++it)
480                     t << "\n\t" << del_statement
481                       << ' ' << escapeFilePath(Option::fixPathToTargetOS((*it).toQString()));
482             } else {
483                 QString files, file;
484                 const int commandlineLimit = 2047; // NT limit, expanded
485                 for (ProStringList::ConstIterator it = list.begin(); it != list.end(); ++it) {
486                     file = ' ' + escapeFilePath(Option::fixPathToTargetOS((*it).toQString()));
487                     if(del_statement.length() + files.length() +
488                        qMax(fixEnvVariables(file).length(), file.length()) > commandlineLimit) {
489                         t << "\n\t" << del_statement << files;
490                         files.clear();
491                     }
492                     files += file;
493                 }
494                 if(!files.isEmpty())
495                     t << "\n\t" << del_statement << files;
496             }
497         }
498     }
499     t << Qt::endl << Qt::endl;
500 
501     t << "distclean: clean " << depVar("DISTCLEAN_DEPS");
502     {
503         const char *clean_targets[] = { "QMAKE_DISTCLEAN", nullptr };
504         for(int i = 0; clean_targets[i]; ++i) {
505             const ProStringList &list = project->values(clean_targets[i]);
506             const QString del_statement("-$(DEL_FILE)");
507             if(project->isActiveConfig("no_delete_multiple_files")) {
508                 for (ProStringList::ConstIterator it = list.begin(); it != list.end(); ++it)
509                     t << "\n\t" << del_statement << " "
510                       << escapeFilePath(Option::fixPathToTargetOS((*it).toQString()));
511             } else {
512                 QString files, file;
513                 const int commandlineLimit = 2047; // NT limit, expanded
514                 for (ProStringList::ConstIterator it = list.begin(); it != list.end(); ++it) {
515                     file = " " + escapeFilePath(Option::fixPathToTargetOS((*it).toQString()));
516                     if(del_statement.length() + files.length() +
517                        qMax(fixEnvVariables(file).length(), file.length()) > commandlineLimit) {
518                         t << "\n\t" << del_statement << files;
519                         files.clear();
520                     }
521                     files += file;
522                 }
523                 if(!files.isEmpty())
524                     t << "\n\t" << del_statement << files;
525             }
526         }
527     }
528     t << "\n\t-$(DEL_FILE) $(DESTDIR_TARGET)\n";
529     {
530         QString ofile = fileFixify(Option::output.fileName());
531         if(!ofile.isEmpty())
532             t << "\t-$(DEL_FILE) " << escapeFilePath(ofile) << Qt::endl;
533     }
534     t << Qt::endl;
535 }
536 
writeIncPart(QTextStream & t)537 void Win32MakefileGenerator::writeIncPart(QTextStream &t)
538 {
539     t << "INCPATH       = ";
540 
541     const ProStringList &incs = project->values("INCLUDEPATH");
542     for(int i = 0; i < incs.size(); ++i) {
543         QString inc = incs.at(i).toQString();
544         inc.replace(QRegExp("\\\\$"), "");
545         if(!inc.isEmpty())
546             t << "-I" << escapeFilePath(inc) << ' ';
547     }
548     t << Qt::endl;
549 }
550 
writeStandardParts(QTextStream & t)551 void Win32MakefileGenerator::writeStandardParts(QTextStream &t)
552 {
553     writeExportedVariables(t);
554 
555     t << "####### Compiler, tools and options\n\n";
556     t << "CC            = " << var("QMAKE_CC") << Qt::endl;
557     t << "CXX           = " << var("QMAKE_CXX") << Qt::endl;
558     t << "DEFINES       = "
559       << varGlue("PRL_EXPORT_DEFINES","-D"," -D"," ")
560       << varGlue("DEFINES","-D"," -D","") << Qt::endl;
561     t << "CFLAGS        = " << var("QMAKE_CFLAGS") << " $(DEFINES)\n";
562     t << "CXXFLAGS      = " << var("QMAKE_CXXFLAGS") << " $(DEFINES)\n";
563 
564     writeIncPart(t);
565     writeLibsPart(t);
566     writeDefaultVariables(t);
567     t << Qt::endl;
568 
569     t << "####### Output directory\n\n";
570     if(!project->values("OBJECTS_DIR").isEmpty())
571         t << "OBJECTS_DIR   = " << escapeFilePath(var("OBJECTS_DIR").remove(QRegExp("\\\\$"))) << Qt::endl;
572     else
573         t << "OBJECTS_DIR   = . \n";
574     t << Qt::endl;
575 
576     t << "####### Files\n\n";
577     t << "SOURCES       = " << valList(escapeFilePaths(project->values("SOURCES")))
578       << " " << valList(escapeFilePaths(project->values("GENERATED_SOURCES"))) << Qt::endl;
579 
580     // do this here so we can set DEST_TARGET to be the complete path to the final target if it is needed.
581     QString orgDestDir = var("DESTDIR");
582     QString destDir = Option::fixPathToTargetOS(orgDestDir, false);
583     if (!destDir.isEmpty() && (orgDestDir.endsWith('/') || orgDestDir.endsWith(Option::dir_sep)))
584         destDir += Option::dir_sep;
585     QString target = QString(project->first("TARGET")+project->first("TARGET_EXT"));
586     project->values("DEST_TARGET").prepend(destDir + target);
587 
588     writeObjectsPart(t);
589 
590     writeExtraCompilerVariables(t);
591     writeExtraVariables(t);
592 
593     t << "DIST          = " << fileVarList("DISTFILES") << ' '
594       << fileVarList("HEADERS") << ' ' << fileVarList("SOURCES") << Qt::endl;
595     t << "QMAKE_TARGET  = " << fileVar("QMAKE_ORIG_TARGET") << Qt::endl;  // unused
596     // The comment is important to maintain variable compatibility with Unix
597     // Makefiles, while not interpreting a trailing-slash as a linebreak
598     t << "DESTDIR        = " << escapeFilePath(destDir) << " #avoid trailing-slash linebreak\n";
599     t << "TARGET         = " << escapeFilePath(target) << Qt::endl;
600     t << "DESTDIR_TARGET = " << fileVar("DEST_TARGET") << Qt::endl;
601     t << Qt::endl;
602 
603     writeImplicitRulesPart(t);
604 
605     t << "####### Build rules\n\n";
606     writeBuildRulesPart(t);
607 
608     if (project->first("TEMPLATE") != "aux") {
609         if (project->isActiveConfig("shared") && !project->values("DLLDESTDIR").isEmpty()) {
610             const ProStringList &dlldirs = project->values("DLLDESTDIR");
611             for (ProStringList::ConstIterator dlldir = dlldirs.begin(); dlldir != dlldirs.end(); ++dlldir) {
612                 t << "\t-$(COPY_FILE) $(DESTDIR_TARGET) "
613                   << escapeFilePath(Option::fixPathToTargetOS((*dlldir).toQString(), false)) << Qt::endl;
614             }
615         }
616         t << Qt::endl;
617 
618         writeRcFilePart(t);
619     }
620 
621     writeMakeQmake(t);
622 
623     QStringList dist_files = fileFixify(Option::mkfile::project_files);
624     if(!project->isEmpty("QMAKE_INTERNAL_INCLUDED_FILES"))
625         dist_files += project->values("QMAKE_INTERNAL_INCLUDED_FILES").toQStringList();
626     if(!project->isEmpty("TRANSLATIONS"))
627         dist_files << var("TRANSLATIONS");
628     if(!project->isEmpty("FORMS")) {
629         const ProStringList &forms = project->values("FORMS");
630         for (ProStringList::ConstIterator formit = forms.begin(); formit != forms.end(); ++formit) {
631             QString ui_h = fileFixify((*formit) + Option::h_ext.first());
632             if(exists(ui_h))
633                 dist_files << ui_h;
634         }
635     }
636     t << "dist:\n\t"
637       << "$(ZIP) " << var("QMAKE_ORIG_TARGET") << ".zip $(SOURCES) $(DIST) "
638       << escapeFilePaths(dist_files).join(' ') << ' ' << fileVar("TRANSLATIONS") << ' ';
639     if(!project->isEmpty("QMAKE_EXTRA_COMPILERS")) {
640         const ProStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
641         for (ProStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
642             const ProStringList &inputs = project->values(ProKey(*it + ".input"));
643             for (ProStringList::ConstIterator input = inputs.begin(); input != inputs.end(); ++input) {
644                 const ProStringList &val = project->values((*input).toKey());
645                 t << escapeFilePaths(val).join(' ') << ' ';
646             }
647         }
648     }
649     t << Qt::endl << Qt::endl;
650 
651     writeCleanParts(t);
652     writeExtraTargets(t);
653     writeExtraCompilerTargets(t);
654     t << Qt::endl << Qt::endl;
655 }
656 
writeLibsPart(QTextStream & t)657 void Win32MakefileGenerator::writeLibsPart(QTextStream &t)
658 {
659     if(project->isActiveConfig("staticlib") && project->first("TEMPLATE") == "lib") {
660         t << "LIBAPP        = " << var("QMAKE_LIB") << Qt::endl;
661         t << "LIBFLAGS      = " << var("QMAKE_LIBFLAGS") << Qt::endl;
662     } else {
663         t << "LINKER        = " << var("QMAKE_LINK") << Qt::endl;
664         t << "LFLAGS        = " << var("QMAKE_LFLAGS") << Qt::endl;
665         t << "LIBS          = " << fixLibFlags("LIBS").join(' ') << ' '
666                                 << fixLibFlags("LIBS_PRIVATE").join(' ') << ' '
667                                 << fixLibFlags("QMAKE_LIBS").join(' ') << ' '
668                                 << fixLibFlags("QMAKE_LIBS_PRIVATE").join(' ') << Qt::endl;
669     }
670 }
671 
writeObjectsPart(QTextStream & t)672 void Win32MakefileGenerator::writeObjectsPart(QTextStream &t)
673 {
674     // Used in both deps and commands.
675     t << "OBJECTS       = " << valList(escapeDependencyPaths(project->values("OBJECTS"))) << Qt::endl;
676 }
677 
writeImplicitRulesPart(QTextStream &)678 void Win32MakefileGenerator::writeImplicitRulesPart(QTextStream &)
679 {
680 }
681 
writeBuildRulesPart(QTextStream &)682 void Win32MakefileGenerator::writeBuildRulesPart(QTextStream &)
683 {
684 }
685 
writeRcFilePart(QTextStream & t)686 void Win32MakefileGenerator::writeRcFilePart(QTextStream &t)
687 {
688     if(!project->values("RC_FILE").isEmpty()) {
689         const ProString res_file = project->first("RES_FILE");
690         const QString rc_file = fileFixify(project->first("RC_FILE").toQString());
691 
692         const ProStringList rcIncPaths = project->values("RC_INCLUDEPATH");
693         QString incPathStr;
694         for (int i = 0; i < rcIncPaths.count(); ++i) {
695             const ProString &path = rcIncPaths.at(i);
696             if (path.isEmpty())
697                 continue;
698             incPathStr += QStringLiteral(" /i ");
699             incPathStr += escapeFilePath(path);
700         }
701 
702         addSourceFile(rc_file, QMakeSourceFileInfo::SEEK_DEPS);
703         const QStringList rcDeps = QStringList(rc_file) << dependencies(rc_file);
704 
705         // The resource tool may use defines. This might be the same defines passed in as the
706         // compiler, since you may use these defines in the .rc file itself.
707         // As the escape syntax for the command line defines for RC is different from that for CL,
708         // we might have to set specific defines for RC.
709         ProString defines = varGlue("RC_DEFINES", " -D", " -D", "");
710         if (defines.isEmpty())
711             defines = ProString(" $(DEFINES)");
712 
713         // Also, we need to add the _DEBUG define manually since the compiler defines this symbol
714         // by itself, and we use it in the automatically created rc file when VERSION is defined
715         // in the .pro file.
716         t << escapeDependencyPath(res_file) << ": "
717           << escapeDependencyPaths(rcDeps).join(' ') << "\n\t"
718           << var("QMAKE_RC") << (project->isActiveConfig("debug") ? " -D_DEBUG" : "")
719           << defines << incPathStr << " -fo " << escapeFilePath(res_file)
720           << ' ' << escapeFilePath(rc_file);
721         t << Qt::endl << Qt::endl;
722     }
723 }
724 
defaultInstall(const QString & t)725 QString Win32MakefileGenerator::defaultInstall(const QString &t)
726 {
727     if((t != "target" && t != "dlltarget") ||
728        (t == "dlltarget" && (project->first("TEMPLATE") != "lib" || !project->isActiveConfig("shared"))) ||
729         project->first("TEMPLATE") == "subdirs" || project->first("TEMPLATE") == "aux")
730        return QString();
731 
732     const QString root = installRoot();
733     ProStringList &uninst = project->values(ProKey(t + ".uninstall"));
734     QString ret;
735     QString targetdir = fileFixify(project->first(ProKey(t + ".path")).toQString(), FileFixifyAbsolute);
736     if(targetdir.right(1) != Option::dir_sep)
737         targetdir += Option::dir_sep;
738 
739     const ProStringList &targets = project->values(ProKey(t + ".targets"));
740     for (int i = 0; i < targets.size(); ++i) {
741         QString src = targets.at(i).toQString(),
742                 dst = escapeFilePath(filePrefixRoot(root, targetdir + src.section('/', -1)));
743         if (!ret.isEmpty())
744             ret += "\n\t";
745         ret += "$(QINSTALL) " + escapeFilePath(Option::fixPathToTargetOS(src, false)) + ' ' + dst;
746         if (!uninst.isEmpty())
747             uninst.append("\n\t");
748         uninst.append("-$(DEL_FILE) " + dst);
749     }
750 
751     if(t == "target" && project->first("TEMPLATE") == "lib") {
752         if(project->isActiveConfig("create_prl") && !project->isActiveConfig("no_install_prl") &&
753            !project->isEmpty("QMAKE_INTERNAL_PRL_FILE")) {
754             QString dst_prl = Option::fixPathToTargetOS(project->first("QMAKE_INTERNAL_PRL_FILE").toQString());
755             int slsh = dst_prl.lastIndexOf(Option::dir_sep);
756             if(slsh != -1)
757                 dst_prl = dst_prl.right(dst_prl.length() - slsh - 1);
758             dst_prl = filePrefixRoot(root, targetdir + dst_prl);
759             if (!ret.isEmpty())
760                 ret += "\n\t";
761             ret += installMetaFile(ProKey("QMAKE_PRL_INSTALL_REPLACE"), project->first("QMAKE_INTERNAL_PRL_FILE").toQString(), dst_prl);
762             if(!uninst.isEmpty())
763                 uninst.append("\n\t");
764             uninst.append("-$(DEL_FILE) " + escapeFilePath(dst_prl));
765         }
766         if(project->isActiveConfig("create_pc")) {
767             QString dst_pc = pkgConfigFileName(false);
768             if (!dst_pc.isEmpty()) {
769                 dst_pc = filePrefixRoot(root, targetdir + dst_pc);
770                 const QString dst_pc_dir = Option::fixPathToTargetOS(fileInfo(dst_pc).path(), false);
771                 if (!dst_pc_dir.isEmpty()) {
772                     if (!ret.isEmpty())
773                         ret += "\n\t";
774                     ret += mkdir_p_asstring(dst_pc_dir, true);
775                 }
776                 if(!ret.isEmpty())
777                     ret += "\n\t";
778                 ret += installMetaFile(ProKey("QMAKE_PKGCONFIG_INSTALL_REPLACE"), pkgConfigFileName(true), dst_pc);
779                 if(!uninst.isEmpty())
780                     uninst.append("\n\t");
781                 uninst.append("-$(DEL_FILE) " + escapeFilePath(dst_pc));
782             }
783         }
784         if(project->isActiveConfig("shared") && !project->isActiveConfig("plugin")) {
785             ProString lib_target = project->first("LIB_TARGET");
786             QString src_targ = escapeFilePath(
787                     (project->isEmpty("DESTDIR") ? QString("$(DESTDIR)") : project->first("DESTDIR"))
788                     + lib_target);
789             QString dst_targ = escapeFilePath(
790                     filePrefixRoot(root, fileFixify(targetdir + lib_target, FileFixifyAbsolute)));
791             if(!ret.isEmpty())
792                 ret += "\n\t";
793             ret += QString("-$(INSTALL_FILE) ") + src_targ + ' ' + dst_targ;
794             if(!uninst.isEmpty())
795                 uninst.append("\n\t");
796             uninst.append("-$(DEL_FILE) " + dst_targ);
797         }
798     }
799 
800     if (t == "dlltarget" || project->values(ProKey(t + ".CONFIG")).indexOf("no_dll") == -1) {
801         QString src_targ = "$(DESTDIR_TARGET)";
802         QString dst_targ = escapeFilePath(
803                 filePrefixRoot(root, fileFixify(targetdir + "$(TARGET)", FileFixifyAbsolute)));
804         if(!ret.isEmpty())
805             ret += "\n\t";
806         ret += QString("-$(INSTALL_FILE) ") + src_targ + ' ' + dst_targ;
807         if(!uninst.isEmpty())
808             uninst.append("\n\t");
809         uninst.append("-$(DEL_FILE) " + dst_targ);
810     }
811     return ret;
812 }
813 
writeDefaultVariables(QTextStream & t)814 void Win32MakefileGenerator::writeDefaultVariables(QTextStream &t)
815 {
816     MakefileGenerator::writeDefaultVariables(t);
817     t << "IDC           = " << (project->isEmpty("QMAKE_IDC") ? QString("idc") : var("QMAKE_IDC"))
818                             << Qt::endl;
819     t << "IDL           = " << (project->isEmpty("QMAKE_IDL") ? QString("midl") : var("QMAKE_IDL"))
820                             << Qt::endl;
821     t << "ZIP           = " << var("QMAKE_ZIP") << Qt::endl;
822     t << "DEF_FILE      = " << fileVar("DEF_FILE") << Qt::endl;
823     t << "RES_FILE      = " << fileVar("RES_FILE") << Qt::endl; // Not on mingw, can't see why not though...
824     t << "SED           = " << var("QMAKE_STREAM_EDITOR") << Qt::endl;
825     t << "MOVE          = " << var("QMAKE_MOVE") << Qt::endl;
826 }
827 
escapeFilePath(const QString & path) const828 QString Win32MakefileGenerator::escapeFilePath(const QString &path) const
829 {
830     QString ret = path;
831     if(!ret.isEmpty()) {
832         if (ret.contains(' ') || ret.contains('\t'))
833             ret = "\"" + ret + "\"";
834         debug_msg(2, "EscapeFilePath: %s -> %s", path.toLatin1().constData(), ret.toLatin1().constData());
835     }
836     return ret;
837 }
838 
escapeDependencyPath(const QString & path) const839 QString Win32MakefileGenerator::escapeDependencyPath(const QString &path) const
840 {
841     QString ret = path;
842     if (!ret.isEmpty()) {
843         static const QRegExp criticalChars(QStringLiteral("([\t #])"));
844         if (ret.contains(criticalChars))
845             ret = "\"" + ret + "\"";
846         debug_msg(2, "EscapeDependencyPath: %s -> %s", path.toLatin1().constData(), ret.toLatin1().constData());
847     }
848     return ret;
849 }
850 
cQuoted(const QString & str)851 QString Win32MakefileGenerator::cQuoted(const QString &str)
852 {
853     QString ret = str;
854     ret.replace(QLatin1Char('\\'), QLatin1String("\\\\"));
855     ret.replace(QLatin1Char('"'), QLatin1String("\\\""));
856     ret.prepend(QLatin1Char('"'));
857     ret.append(QLatin1Char('"'));
858     return ret;
859 }
860 
fullTargetVariable() const861 ProKey Win32MakefileGenerator::fullTargetVariable() const
862 {
863     return "DEST_TARGET";
864 }
865 
866 QT_END_NAMESPACE
867