File: SC_Lib_Cintf.cpp

package info (click to toggle)
supercollider 1%3A3.13.0%2Brepack-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 80,296 kB
  • sloc: cpp: 476,363; lisp: 84,680; ansic: 77,685; sh: 25,509; python: 7,909; makefile: 3,440; perl: 1,964; javascript: 974; xml: 826; java: 677; yacc: 314; lex: 175; objc: 152; ruby: 136
file content (407 lines) | stat: -rw-r--r-- 13,815 bytes parent folder | download | duplicates (4)
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
/*
    SuperCollider real time audio synthesis system
    Copyright (c) 2002 James McCartney. All rights reserved.
    http://www.audiosynth.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
*/


#include "SC_Lib_Cintf.h"
#include "SC_CoreAudio.h"
#include "SC_UnitDef.h"
#include "SC_BufGen.h"
#include "SC_World.h"
#include "SC_WorldOptions.h"
#include "SC_StringParser.h"
#include "SC_InterfaceTable.h"
#include "SC_Filesystem.hpp"
#include "ErrorMessage.hpp" // for apiVersionMismatch, apiVersionMissing
#include <stdexcept>
#include <iostream>

#ifndef _MSC_VER
#    include <dirent.h>
#endif // _MSC_VER

#ifdef _WIN32
#    include "SC_Win32Utils.h"
#else
#    include <dlfcn.h>
#    include <libgen.h>
#    include <sys/param.h>
#endif // _WIN32

#include <boost/filesystem/path.hpp> // path
#include <boost/filesystem/operations.hpp> // is_directory

#ifdef __APPLE__
extern "C" {
#    include <mach-o/dyld.h>
#    include <mach-o/getsect.h>
}
char gTempVal;
#endif // __APPLE__

namespace bfs = boost::filesystem;

Malloc gMalloc;
HashTable<SC_LibCmd, Malloc>* gCmdLib;
HashTable<struct UnitDef, Malloc>* gUnitDefLib = nullptr;
HashTable<struct BufGen, Malloc>* gBufGenLib = nullptr;
HashTable<struct PlugInCmd, Malloc>* gPlugInCmds = nullptr;
extern struct InterfaceTable gInterfaceTable;
SC_LibCmd* gCmdArray[NUMBER_OF_COMMANDS];

void initMiscCommands();
static bool PlugIn_LoadDir(const bfs::path& dir, bool reportError);
std::vector<void*> open_handles;
#ifdef __APPLE__
void read_section(const struct mach_header* mhp, unsigned long slide, const char* segname, const char* sectname) {
    u_int32_t size;
    char* sect = getsectdatafromheader(mhp, segname, sectname, &size);
    if (!sect)
        return;

    char* start = sect + slide;
    char* end = start + size;

    while (start != end) {
        gTempVal += *(char*)start;
        start++;
    }
}
#endif

extern void IO_Load(InterfaceTable* table);
extern void Osc_Load(InterfaceTable* table);
extern void Delay_Load(InterfaceTable* table);
extern void BinaryOp_Load(InterfaceTable* table);
extern void Filter_Load(InterfaceTable* table);
extern void Gendyn_Load(InterfaceTable* table);
extern void LF_Load(InterfaceTable* table);
extern void Noise_Load(InterfaceTable* table);
extern void MulAdd_Load(InterfaceTable* table);
extern void Grain_Load(InterfaceTable* table);
extern void Pan_Load(InterfaceTable* table);
extern void Reverb_Load(InterfaceTable* table);
extern void Trigger_Load(InterfaceTable* table);
extern void UnaryOp_Load(InterfaceTable* table);
extern void DiskIO_Load(InterfaceTable* table);
extern void Test_Load(InterfaceTable* table);
extern void PhysicalModeling_Load(InterfaceTable* table);
extern void Demand_Load(InterfaceTable* table);
extern void DynNoise_Load(InterfaceTable* table);
extern void FFT_UGens_Load(InterfaceTable* table);
extern void iPhone_Load(InterfaceTable* table);


void deinitialize_library() {
#ifdef _WIN32
    for (void* ptrhinstance : open_handles) {
        HINSTANCE hinstance = (HINSTANCE)ptrhinstance;
        void* ptr = (void*)GetProcAddress(hinstance, "unload");
        if (ptr) {
            UnLoadPlugInFunc unloadFunc = (UnLoadPlugInFunc)ptr;
            (*unloadFunc)();
        }
    }
    // FreeLibrary dlclose(handle);
#else
    for (void* handle : open_handles) {
        void* ptr = dlsym(handle, "unload");
        if (ptr) {
            UnLoadPlugInFunc unloadFunc = (UnLoadPlugInFunc)ptr;
            (*unloadFunc)();
        }
    }
#endif
    open_handles.clear();
}
void initialize_library(const char* uGensPluginPath) {
    gCmdLib = new HashTable<SC_LibCmd, Malloc>(&gMalloc, 64, true);
    gUnitDefLib = new HashTable<UnitDef, Malloc>(&gMalloc, 512, true);
    gBufGenLib = new HashTable<BufGen, Malloc>(&gMalloc, 512, true);
    gPlugInCmds = new HashTable<PlugInCmd, Malloc>(&gMalloc, 64, true);

    initMiscCommands();

#ifdef STATIC_PLUGINS
    IO_Load(&gInterfaceTable);
    Osc_Load(&gInterfaceTable);
    Delay_Load(&gInterfaceTable);
    BinaryOp_Load(&gInterfaceTable);
    Filter_Load(&gInterfaceTable);
    Gendyn_Load(&gInterfaceTable);
    LF_Load(&gInterfaceTable);
    Noise_Load(&gInterfaceTable);
    MulAdd_Load(&gInterfaceTable);
    Grain_Load(&gInterfaceTable);
    Pan_Load(&gInterfaceTable);
    Reverb_Load(&gInterfaceTable);
    Trigger_Load(&gInterfaceTable);
    UnaryOp_Load(&gInterfaceTable);
    DiskIO_Load(&gInterfaceTable);
    PhysicalModeling_Load(&gInterfaceTable);
    Test_Load(&gInterfaceTable);
    Demand_Load(&gInterfaceTable);
    DynNoise_Load(&gInterfaceTable);
#    if defined(SC_IPHONE) && !TARGET_IPHONE_SIMULATOR
    iPhone_Load(&gInterfaceTable);
#    endif
    FFT_UGens_Load(&gInterfaceTable);
    return;
#endif // STATIC_PLUGINS

    // If uGensPluginPath is supplied, it is exclusive.
    bool loadUGensExtDirs = true;
    if (uGensPluginPath) {
        loadUGensExtDirs = false;
        SC_StringParser sp(uGensPluginPath, SC_STRPARSE_PATHDELIMITER);
        while (!sp.AtEnd()) {
            PlugIn_LoadDir(const_cast<char*>(sp.NextToken()), true);
        }
    }

    using DirName = SC_Filesystem::DirName;

    if (loadUGensExtDirs) {
#ifdef SC_PLUGIN_DIR
        // load globally installed plugins
        if (bfs::is_directory(SC_PLUGIN_DIR)) {
            PlugIn_LoadDir(SC_PLUGIN_DIR, true);
        }
#endif // SC_PLUGIN_DIR
       // load default plugin directory
        const bfs::path pluginDir = SC_Filesystem::instance().getDirectory(DirName::Resource) / SC_PLUGIN_DIR_NAME;

        if (bfs::is_directory(pluginDir)) {
            PlugIn_LoadDir(pluginDir, true);
        }
    }

    // get extension directories
    if (loadUGensExtDirs) {
        // load system extension plugins
        const bfs::path sysExtDir = SC_Filesystem::instance().getDirectory(DirName::SystemExtension);
        PlugIn_LoadDir(sysExtDir, false);

        // load user extension plugins
        const bfs::path userExtDir = SC_Filesystem::instance().getDirectory(DirName::UserExtension);
        PlugIn_LoadDir(userExtDir, false);

        // load user plugin directories
        SC_StringParser sp(getenv("SC_PLUGIN_PATH"), SC_STRPARSE_PATHDELIMITER);
        while (!sp.AtEnd()) {
            PlugIn_LoadDir(sp.NextToken(), true);
        }
    }
#ifdef __APPLE__
    /* on darwin plugins are lazily loaded (dlopen uses mmap internally), which can produce audible
        glitches when UGens have to be paged-in. to work around this we preload all the plugins by
        iterating through their memory space. */

#    ifndef __x86_64__
    /* seems to cause a stack corruption on llvm-gcc-4.2, sdk 10.5 on 10.6 */

    unsigned long images = _dyld_image_count();
    for (unsigned long i = 0; i < images; i++) {
        const mach_header* hdr = _dyld_get_image_header(i);
        unsigned long slide = _dyld_get_image_vmaddr_slide(i);
        const char* name = _dyld_get_image_name(i);
        uint32_t size;
        char* sect;

        if (!strcmp(name + (strlen(name) - 4), ".scx")) {
            read_section(hdr, slide, "__TEXT", "__text");
            read_section(hdr, slide, "__TEXT", "__const");
            read_section(hdr, slide, "__TEXT", "__cstring");
            read_section(hdr, slide, "__TEXT", "__picsymbol_stub");
            read_section(hdr, slide, "__TEXT", "__symbol_stub");
            read_section(hdr, slide, "__TEXT", "__const");
            read_section(hdr, slide, "__TEXT", "__literal4");
            read_section(hdr, slide, "__TEXT", "__literal8");

            read_section(hdr, slide, "__DATA", "__data");
            read_section(hdr, slide, "__DATA", "__la_symbol_ptr");
            read_section(hdr, slide, "__DATA", "__nl_symbol_ptr");
            read_section(hdr, slide, "__DATA", "__dyld");
            read_section(hdr, slide, "__DATA", "__const");
            read_section(hdr, slide, "__DATA", "__mod_init_func");
            read_section(hdr, slide, "__DATA", "__bss");
            read_section(hdr, slide, "__DATA", "__common");

            read_section(hdr, slide, "__IMPORT", "__jump_table");
            read_section(hdr, slide, "__IMPORT", "__pointers");
        }
    }
#    endif // __x86_64__

#endif // ifdef __APPLE__
}

typedef int (*InfoFunction)();

bool checkAPIVersion(void* f, const char* filename) {
    using namespace std;
    using namespace scsynth;

    if (f) {
        InfoFunction fn = (InfoFunction)f;
        int pluginVersion = (*fn)();
        if (pluginVersion == sc_api_version)
            return true;
        else
            cout << ErrorMessage::apiVersionMismatch(filename, sc_api_version, pluginVersion) << endl;
    } else {
        cout << ErrorMessage::apiVersionNotFound(filename) << endl;
    }

    return false;
}

bool checkServerVersion(void* f, const char* filename) {
    if (f) {
        InfoFunction fn = (InfoFunction)f;
        if ((*fn)() == 1)
            return false;
    }
    return true;
}

static bool PlugIn_Load(const bfs::path& filename) {
#ifdef _WIN32
    HINSTANCE hinstance = LoadLibraryW(filename.wstring().c_str());
    // here, we have to use a utf-8 version of the string for printing
    // because the native encoding on Windows is utf-16.
    const std::string filename_utf8_str = SC_Codecvt::path_to_utf8_str(filename);
    if (!hinstance) {
        char* s;
        DWORD lastErr = GetLastError();
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
                      lastErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&s, 0, NULL);
        scprintf("*** ERROR: LoadLibrary '%s' err '%s'\n", filename_utf8_str.c_str(), s);
        LocalFree(s);
        return false;
    }

    void* apiVersionPtr = (void*)GetProcAddress(hinstance, "api_version");
    if (!checkAPIVersion(apiVersionPtr, filename_utf8_str.c_str())) {
        FreeLibrary(hinstance);
        return false;
    }

    void* serverCheckPtr = (void*)GetProcAddress(hinstance, "server_type");
    if (!checkServerVersion(serverCheckPtr, filename_utf8_str.c_str())) {
        FreeLibrary(hinstance);
        return false;
    }

    void* ptr = (void*)GetProcAddress(hinstance, "load");
    if (!ptr) {
        char* s;
        FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
                      GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char*)&s, 0, NULL);
        scprintf("*** ERROR: GetProcAddress err '%s'\n", s);
        LocalFree(s);

        FreeLibrary(hinstance);
        return false;
    }

    LoadPlugInFunc loadFunc = (LoadPlugInFunc)ptr;
    (*loadFunc)(&gInterfaceTable);

    // FIXME: at the moment we never call FreeLibrary() on a loaded plugin
    open_handles.push_back(hinstance);
    return true;

#else // (ifndef _WIN32)
    void* handle = dlopen(filename.c_str(), RTLD_NOW);

    if (!handle) {
        scprintf("*** ERROR: dlopen '%s' err '%s'\n", filename.c_str(), dlerror());
        dlclose(handle);
        return false;
    }

    void* apiVersionPtr = (void*)dlsym(handle, "api_version");
    if (!checkAPIVersion(apiVersionPtr, filename.c_str())) {
        dlclose(handle);
        return false;
    }

    void* serverCheckPtr = (void*)dlsym(handle, "server_type");
    if (!checkServerVersion(serverCheckPtr, filename.c_str())) {
        dlclose(handle);
        return false;
    }

    void* ptr = dlsym(handle, "load");
    if (!ptr) {
        scprintf("*** ERROR: dlsym load err '%s'\n", dlerror());
        dlclose(handle);
        return false;
    }

    LoadPlugInFunc loadFunc = (LoadPlugInFunc)ptr;
    (*loadFunc)(&gInterfaceTable);

    open_handles.push_back(handle);
    return true;

#endif // _WIN32
}

static bool PlugIn_LoadDir(const bfs::path& dir, bool reportError) {
    boost::system::error_code ec;
    bfs::recursive_directory_iterator rditer(dir, bfs::symlink_option::recurse, ec);

    if (ec) {
        if (reportError) {
            scprintf("*** ERROR: open directory failed '%s': %s\n", SC_Codecvt::path_to_utf8_str(dir).c_str(),
                     ec.message().c_str());
            fflush(stdout);
        }
        return false;
    }

    while (rditer != bfs::end(rditer)) {
        const bfs::path path = *rditer;

        if (bfs::is_directory(path)) {
            if (SC_Filesystem::instance().shouldNotCompileDirectory(path))
                rditer.no_push();
            else
                ; // do nothing; recursion for free
        } else if (path.extension() == SC_PLUGIN_EXT) {
            // don't need to check result: PlugIn_Load does its own error handling and printing.
            // A `false` return value here just means that loading didn't occur, which is not
            // an error condition for us.
            PlugIn_Load(path);
        } else {
            // not a plugin, do nothing
        }

        rditer.increment(ec);
        if (ec) {
            scprintf("*** ERROR: Could not iterate on directory '%s': %s\n", SC_Codecvt::path_to_utf8_str(path).c_str(),
                     ec.message().c_str());
            return false;
        }
    }

    return true;
}