blob: 09a9d3969f577763ec018413ab75a825dd3d8cd9 [file] [log] [blame]
Nan Zhangced27512017-06-19 18:01:34 -07001// Copyright 2017 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Nan Zhangced27512017-06-19 18:01:34 -070015#include <Python.h>
16#include <android-base/file.h>
17#include <osdefs.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <string>
21
22int main(int argc, char *argv[]) {
Nan Zhangced27512017-06-19 18:01:34 -070023 // PYTHONEXECUTABLE is only used on MacOs X, when the Python interpreter
24 // embedded in an application bundle. It is not sure that we have this use case
Dan Willemseneba50a52018-11-16 17:27:26 -080025 // for Android hermetic Python. So remove this environment variable to make
26 // our self-contained environment more strict.
Nan Zhangced27512017-06-19 18:01:34 -070027 // For user (.py) program, it can access hermetic .par file path through
28 // sys.argv[0].
29 unsetenv(const_cast<char *>("PYTHONEXECUTABLE"));
30
Dan Willemseneba50a52018-11-16 17:27:26 -080031 // Always enable Python "-s" option. We don't need user-site directories,
32 // everything's supposed to be hermetic.
33 Py_NoUserSiteDirectory = 1;
34
35 // Ignore PYTHONPATH and PYTHONHOME from the environment.
36 Py_IgnoreEnvironmentFlag = 1;
37
38 Py_DontWriteBytecodeFlag = 1;
39
Nan Zhangced27512017-06-19 18:01:34 -070040 // Resolving absolute path based on argv[0] is not reliable since it may
41 // include something unusable, too bad.
42 // android::base::GetExecutablePath() also handles for Darwin/Windows.
43 std::string executable_path = android::base::GetExecutablePath();
44
Dan Willemseneba50a52018-11-16 17:27:26 -080045 int new_argc = argc + 1;
46 char **new_argv = reinterpret_cast<char**>(calloc(new_argc, sizeof(*argv)));
47
48 // Inject the path to our binary into argv[1] so the Py_Main won't parse any
49 // other options, and will execute the __main__.py script inside the zip file
50 // attached to our executable.
51 new_argv[0] = argv[0];
52 new_argv[1] = strdup(executable_path.c_str());
53 for (int i = 1; i < argc; i++) {
54 new_argv[i+1] = argv[i];
Nan Zhangced27512017-06-19 18:01:34 -070055 }
56
Dan Willemseneba50a52018-11-16 17:27:26 -080057 return Py_Main(new_argc, new_argv);
Nan Zhangced27512017-06-19 18:01:34 -070058}