aboutsummaryrefslogtreecommitdiff
path: root/build2/cc/windows-rpath.cxx
blob: 9ad260252ed0f780be22f5f1d5ac1e8c1dec2d3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// file      : build2/cc/windows-rpath.cxx -*- C++ -*-
// copyright : Copyright (c) 2014-2019 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

#include <errno.h> // E*

#include <build2/scope.hxx>
#include <build2/context.hxx>
#include <build2/variable.hxx>
#include <build2/algorithm.hxx>
#include <build2/filesystem.hxx>
#include <build2/diagnostics.hxx>

#include <build2/bin/target.hxx>

#include <build2/cc/link-rule.hxx>

using namespace std;
using namespace butl;

namespace build2
{
  namespace cc
  {
    // Provide limited emulation of the rpath functionality on Windows using a
    // side-by-side assembly. In a nutshell, the idea is to create an assembly
    // with links to all the prerequisite DLLs.
    //
    // Note that currently our assemblies contain all the DLLs that the
    // executable depends on, recursively. The alternative approach could be
    // to also create assemblies for DLLs. This appears to be possible (but we
    // will have to use the resource ID 2 for such a manifest). And it will
    // probably be necessary for DLLs that are loaded dynamically with
    // LoadLibrary(). The tricky part is how such nested assemblies will be
    // found. Since we are effectively (from the loader's point of view)
    // copying the DLLs, we will also have to copy their assemblies (because
    // the loader looks for them in the same directory as the DLL). It's not
    // clear how well such nested assemblies are supported (e.g., in Wine).
    //
    // What if the DLL is in the same directory as the executable, will it
    // still be found even if there is an assembly? On the other hand,
    // handling it as any other won't hurt us much.
    //
    using namespace bin;

    // Return the greatest (newest) timestamp of all the DLLs that we will be
    // adding to the assembly or timestamp_nonexistent if there aren't any.
    //
    timestamp link_rule::
    windows_rpath_timestamp (const file& t,
                             const scope& bs,
                             action a,
                             linfo li) const
    {
      timestamp r (timestamp_nonexistent);

      // We need to collect all the DLLs, so go into implementation of both
      // shared and static (in case they depend on shared).
      //
      auto imp = [] (const file&, bool) {return true;};

      auto lib = [&r] (const file* const* lc,
                       const string& f,
                       lflags,
                       bool sys)
      {
        const file* l (lc != nullptr ? *lc : nullptr);

        // We don't rpath system libraries.
        //
        if (sys)
          return;

        // Skip static libraries.
        //
        if (l != nullptr)
        {
          // This can be an "undiscovered" DLL (see search_library()).
          //
          if (!l->is_a<libs> () || l->path ().empty ()) // Also covers binless.
            return;
        }
        else
        {
          // This is an absolute path and we need to decide whether it is
          // a shared or static library.
          //
          // @@ This is so broken: we don't link to DLLs, we link to .lib or
          //    .dll.a! Should we even bother? Maybe only for "our" DLLs
          //    (.dll.lib/.dll.a)? But the DLL can also be in a different
          //    directory (lib/../bin).
          //
          //    Though this can happen on MinGW with direct DLL link...
          //
          size_t p (path::traits_type::find_extension (f));

          if (p == string::npos || casecmp (f.c_str () + p + 1, "dll") != 0)
            return;
        }

        // Ok, this is a DLL.
        //
        timestamp t (l != nullptr
                     ? l->load_mtime ()
                     : mtime (f.c_str ()));

        if (t > r)
          r = t;
      };

      for (const prerequisite_target& pt: t.prerequisite_targets[a])
      {
        if (pt == nullptr || pt.adhoc)
          continue;

        bool la;
        const file* f;

        if ((la = (f = pt->is_a<liba>  ())) ||
            (la = (f = pt->is_a<libux> ())) || // See through.
            (     f = pt->is_a<libs>  ()))
          process_libraries (a, bs, li, sys_lib_dirs,
                             *f, la, pt.data,
                             imp, lib, nullptr, true);
      }

      return r;
    }

    // Like *_timestamp() but actually collect the DLLs (and weed out the
    // duplicates).
    //
    auto link_rule::
    windows_rpath_dlls (const file& t,
                        const scope& bs,
                        action a,
                        linfo li) const -> windows_dlls
    {
      windows_dlls r;

      auto imp = [] (const file&, bool) {return true;};

      auto lib = [&r, &bs] (const file* const* lc,
                            const string& f,
                            lflags,
                            bool sys)
      {
        const file* l (lc != nullptr ? *lc : nullptr);

        if (sys)
          return;

        if (l != nullptr)
        {
          if (l->is_a<libs> () && !l->path ().empty ()) // Also covers binless.
          {
            // Get .pdb if there is one.
            //
            const target_type* tt (bs.find_target_type ("pdb"));
            const target* pdb (tt != nullptr
                               ? find_adhoc_member (*l, *tt)
                               : nullptr);
            r.insert (
              windows_dll {
                f,
                pdb != nullptr ? &pdb->as<file> ().path ().string () : nullptr,
                string ()
              });
          }
        }
        else
        {
          size_t p (path::traits_type::find_extension (f));

          if (p != string::npos && casecmp (f.c_str () + p + 1, "dll") == 0)
          {
            // See if we can find a corresponding .pdb.
            //
            windows_dll wd {f, nullptr, string ()};
            string& pdb (wd.pdb_storage);

            // First try "our" naming: foo.dll.pdb.
            //
            pdb = f;
            pdb += ".pdb";

            if (!exists (path (pdb)))
            {
              // Then try the usual naming: foo.pdb.
              //
              pdb.assign (f, 0, p);
              pdb += ".pdb";

              if (!exists (path (pdb)))
                pdb.clear ();
            }

            if (!pdb.empty ())
              wd.pdb = &pdb;

            r.insert (move (wd));
          }
        }
      };

      for (const prerequisite_target& pt: t.prerequisite_targets[a])
      {
        if (pt == nullptr || pt.adhoc)
          continue;

        bool la;
        const file* f;

        if ((la = (f = pt->is_a<liba>  ())) ||
            (la = (f = pt->is_a<libux> ())) || // See through.
            (      f = pt->is_a<libs>  ()))
          process_libraries (a, bs, li, sys_lib_dirs,
                             *f, la, pt.data,
                             imp, lib, nullptr, true);
      }

      return r;
    }

    const char*
    windows_manifest_arch (const string& tcpu); // windows-manifest.cxx

    // The ts argument should be the DLLs timestamp returned by *_timestamp().
    //
    // The scratch argument should be true if the DLL set has changed and we
    // need to regenerate everything from scratch. Otherwise, we try to avoid
    // unnecessary work by comparing the DLLs timestamp against the assembly
    // manifest file.
    //
    void link_rule::
    windows_rpath_assembly (const file& t,
                            const scope& bs,
                            action a,
                            linfo li,
                            const string& tcpu,
                            timestamp ts,
                            bool scratch) const
    {
      // Assembly paths and name.
      //
      dir_path ad (path_cast<dir_path> (t.path () + ".dlls"));
      string an (ad.leaf ().string ());
      path am (ad / path (an + ".manifest"));

      // First check if we actually need to do anything. Since most of the
      // time we won't, we don't want to combine it with the *_dlls() call
      // below which allocates memory, etc.
      //
      if (!scratch)
      {
        // The corner case here is when _timestamp() returns nonexistent
        // signalling that there aren't any DLLs but the assembly manifest
        // file exists. This, however, can only happen if we somehow managed
        // to transition from the "have DLLs" state to "no DLLs" without going
        // through the "from scratch" update. Actually this can happen when
        // switching to update-for-install.
        //
        if (ts != timestamp_nonexistent && ts <= mtime (am))
          return;
      }

      // Next collect the set of DLLs that will be in our assembly. We need to
      // do this recursively which means we may end up with duplicates. Also,
      // it is possible that there aren't/no longer are any DLLs which means
      // we just need to clean things up.
      //
      bool empty (ts == timestamp_nonexistent);

      windows_dlls dlls;
      if (!empty)
        dlls = windows_rpath_dlls (t, bs, a, li);

      // Clean the assembly directory and make sure it exists. Maybe it would
      // have been faster to overwrite the existing manifest rather than
      // removing the old one and creating a new one. But this is definitely
      // simpler.
      //
      {
        rmdir_status s (build2::rmdir_r (ad, empty, 3));

        if (empty)
          return;

        if (s == rmdir_status::not_exist)
          mkdir (ad, 3);
      }

      // Symlink or copy the DLLs.
      //
      {
        const scope& as (*t.root_scope ().weak_scope ()); // Amalgamation.

        auto link = [&as, &ad] (const path& f, const path& l)
        {
          auto print = [&f, &l] (const char* cmd)
          {
            if (verb >= 3)
              text << cmd << ' ' << f << ' ' << l;
          };

          // First we try to create a symlink. If that fails (e.g., "Windows
          // happens"), then we resort to hard links. If that doesn't work
          // out either (e.g., not on the same filesystem), then we fall back
          // to copies. So things are going to get a bit nested.
          //
          try
          {
            // For the symlink use a relative target path if both paths are
            // part of the same amalgamation. This way if the amalgamation is
            // moved as a whole, the links will remain valid.
            //
            if (!dry_run)
            {
              if (f.sub (as.out_path ()))
                mksymlink (f.relative (ad), l);
              else
                mksymlink (f, l);
            }

            print ("ln -s");
          }
          catch (const system_error& e)
          {
            // Note: can never end up here on dry-run.

            // Note that we are not guaranteed (here and below) that the
            // system_error exception is of the generic category.
            //
            int c (e.code ().value ());
            if (!(e.code ().category () == generic_category () &&
                  (c == ENOSYS || // Not implemented.
                   c == EPERM)))  // Not supported by the filesystem(s).
            {
              print ("ln -s");
              fail << "unable to create symlink " << l << ": " << e;
            }

            try
            {
              mkhardlink (f, l);
              print ("ln");
            }
            catch (const system_error& e)
            {
              c = e.code ().value ();
              if (!(e.code ().category () == generic_category () &&
                  (c == ENOSYS || // Not implemented.
                   c == EPERM  || // Not supported by the filesystem(s).
                   c == EXDEV)))  // On different filesystems.
              {
                print ("ln");
                fail << "unable to create hardlink " << l << ": " << e;
              }

              try
              {
                cpfile (f, l);
                print ("cp");
              }
              catch (const system_error& e)
              {
                print ("cp");
                fail << "unable to create copy " << l << ": " << e;
              }
            }
          }
        };

        for (const windows_dll& wd: dlls)
        {
          //@@ Would be nice to avoid copying. Perhaps reuse buffers
          //   by adding path::assign() and traits::leaf().
          //
          path dp (wd.dll);     // DLL path.
          path dn (dp.leaf ()); // DLL name.

          link (dp, ad / dn);

          // Link .pdb if there is one.
          //
          if (wd.pdb != nullptr)
          {
            path pp (*wd.pdb);
            link (pp, ad / pp.leaf ());
          }
        }
      }

      if (verb >= 3)
        text << "cat >" << am;

      if (dry_run)
        return;

      auto_rmfile rm (am);

      try
      {
        ofdstream os (am);

        const char* pa (windows_manifest_arch (tcpu));

        os << "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n"
           << "<assembly xmlns='urn:schemas-microsoft-com:asm.v1'\n"
           << "          manifestVersion='1.0'>\n"
           << "  <assemblyIdentity name='" << an << "'\n"
           << "                    type='win32'\n"
           << "                    processorArchitecture='" << pa << "'\n"
           << "                    version='0.0.0.0'/>\n";



        for (const windows_dll& wd: dlls)
          os << "  <file name='" << path (wd.dll).leaf () << "'/>\n";

        os << "</assembly>\n";

        os.close ();
        rm.cancel ();
      }
      catch (const io_error& e)
      {
        fail << "unable to write to " << am << ": " << e;
      }
    }
  }
}