1/*
2 * Copyright 2012 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include <dlfcn.h>
9#include <stdio.h>
10
11void usage() {
12    printf("[USAGE] skia_launcher program_name [options]\n");
13    printf("  program_name: the skia program you want to launch (e.g. tests, bench)\n");
14    printf("  options: options specific to the program you are launching\n");
15}
16
17bool file_exists(const char* fileName) {
18    FILE* file = fopen(fileName, "r");
19    if (file) {
20        fclose(file);
21        return true;
22    }
23    return false;
24}
25
26int launch_app(int (*app_main)(int, const char**), int argc,
27        const char** argv) {
28    return (*app_main)(argc, argv);
29}
30
31void* load_library(const char* appLocation, const char* libraryName)
32{
33     // attempt to lookup the location of the shared libraries
34    char libraryLocation[100];
35    sprintf(libraryLocation, "%s/lib%s.so", appLocation, libraryName);
36    if (!file_exists(libraryLocation)) {
37        printf("ERROR: Unable to find the '%s' library in the Skia App.\n", libraryName);
38        printf("ERROR: Did you provide the correct program_name?\n");
39        usage();
40        return NULL;
41    }
42
43    // load the appropriate library
44    void* appLibrary = dlopen(libraryLocation, RTLD_LOCAL | RTLD_LAZY);
45    if (!appLibrary) {
46        printf("ERROR: Unable to open the shared library.\n");
47        printf("ERROR: %s", dlerror());
48        return NULL;
49    }
50
51    return appLibrary;
52}
53
54int main(int argc, const char** argv) {
55
56    // check that the program name was specified
57    if (argc < 2) {
58        printf("ERROR: No program_name was specified\n");
59        usage();
60        return -1;
61    }
62
63    // attempt to lookup the location of the skia app
64    const char* appLocation = "/data/local/tmp";
65    if (!file_exists(appLocation)) {
66        printf("ERROR: Unable to find /data/local/tmp on the device.\n");
67        return -1;
68    }
69
70#if defined(SKIA_DLL)
71    // load the local skia shared library
72    void* skiaLibrary = load_library(appLocation, "skia_android");
73    if (NULL == skiaLibrary)
74    {
75        return -1;
76    }
77#endif
78
79    // load the appropriate library
80    void* appLibrary = load_library(appLocation, argv[1]);
81    if (NULL == appLibrary) {
82        return -1;
83    }
84
85    // find the address of the main function
86    int (*app_main)(int, const char**);
87    *(void **) (&app_main) = dlsym(appLibrary, "main");
88
89    if (!app_main) {
90        printf("ERROR: Unable to load the main function of the selected program.\n");
91        printf("ERROR: %s\n", dlerror());
92        return -1;
93    }
94
95    // pass all additional arguments to the main function
96    return launch_app(app_main, argc - 1, ++argv);
97}
98