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
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#***********************************************************************
# This file is part of OpenMolcas. *
# *
# OpenMolcas is free software; you can redistribute it and/or modify *
# it under the terms of the GNU Lesser General Public License, v. 2.1. *
# OpenMolcas is distributed in the hope that it will be useful, but it *
# is provided "as is" and without any express or implied warranties. *
# For more details see the full text of the license in the file *
# LICENSE or in <http://www.gnu.org/licenses/>. *
# *
# Copyright (C) 2015,2017,2018,2022,2024, Ignacio Fdez. Galván *
#***********************************************************************
'''
This exports pymolcas to a single-file python script that can be copied around.
It still uses python and it's trivial to recover the original files (although
without comments). Obfuscation is not the goal here, just getting something
that's easy to run, move and distribute.
'''
from __future__ import (unicode_literals, division, absolute_import, print_function)
try:
from builtins import (bytes, str)
except:
from future.builtins import (bytes, str)
from io import open
import sys, zlib, base64, os, stat, subprocess
sys.dont_write_bytecode = True
files = ['tee', 'molcas_aux', 'emil_grammar', 'simpleeval', 'abstract_flow', 'emil_parse', 'python_parse', 'check_test', 'validate', 'molcas_wrapper', 'pymolcas']
try:
exe_name = sys.argv[1]
except:
exe_name = 'pymolcas'
obfuscate = False # only obfuscate the "wrapper", not the modules' code (yet)
try:
import pyminifier.minification as pm
compact = True
except ImportError:
compact = False
compress_and_b64 = True
def wrap(text, width):
lines = []
l = 0
while (l < len(text)):
r = min(l+width,len(text)+1)
lines.append(text[l:r])
l = r
return '\n'.join(lines)
def minify(string):
string = pm.remove_comments_and_docstrings(string)
string = pm.multiline_indicator.sub('', string)
string = pm.fix_empty_methods(string)
string = pm.join_multiline_pairs(string)
string = pm.join_multiline_pairs(string, '[]')
string = pm.join_multiline_pairs(string, '{}')
string = pm.remove_blank_lines(string)
string = pm.reduce_operators(string)
string = pm.dedent(string)
return string
def find_interpreter():
exe = sys.executable
if exe is None:
return None
# If python, python3 or python2 point to the current executable, use those instead
try:
p = subprocess.check_output(['/usr/bin/env','python','-c','import sys; print(sys.executable)']).decode().strip()
if os.path.realpath(p2) == os.path.realpath(exe):
return '/usr/bin/env python'
except:
pass
try:
p3 = subprocess.check_output(['/usr/bin/env','python3','-c','import sys; print(sys.executable)']).decode().strip()
if os.path.realpath(p3) == os.path.realpath(exe):
return '/usr/bin/env python3'
except:
pass
try:
p2 = subprocess.check_output(['/usr/bin/env','python2','-c','import sys; print(sys.executable)']).decode().strip()
if os.path.realpath(p2) == os.path.realpath(exe):
return '/usr/bin/env python2'
except:
pass
return exe
if (compress_and_b64):
code = 'import zlib,base64;exec(zlib.decompress(base64.b64decode(bytes(m[1],\\\'ascii\\\'))),module.__dict__);del zlib,base64'
else:
code = 'exec(m[1],module.__dict__)'
hexcode = ''.join('{:02x}'.format(c) for c in bytes(code, 'ascii'))
from pymolcas import warning
mods_name = 'M' if obfuscate else 'modules'
failed = False
with open(exe_name, 'w', encoding='utf-8') as f:
interpreter = find_interpreter()
if (interpreter is None):
interpreter = '/usr/bin/env python'
f.write('''#!{0}
# -*- coding: utf-8 -*-
#{1}
{2} = [
'''.format(interpreter, warning.replace('\n','\n#'), mods_name))
try:
for i in files:
filename = '{0}.py'.format(i)
with open(filename, 'r', encoding='utf-8') as fin:
content = fin.read()
if (compact):
try:
#python3
content = minify(content)
except UnicodeEncodeError:
#python2
content = minify(bytes(content, 'utf-8'))
if (compress_and_b64):
content = str(base64.b64encode(zlib.compress(bytes(content, 'utf-8'))), 'utf-8')
content = wrap(content, 120)
fmt = " ['{0}', '''\n{1}\n'''],\n\n"
else:
fmt = " ['{0}', r\"\"\"\n{1}\n\"\"\"],\n\n"
content = bytes(content, 'utf-8')
if (obfuscate):
name_i = ''.join('{:02x}'.format(c) for c in bytes(i, 'ascii'))
else:
name_i = i
f.write(fmt.format(name_i, content.decode('utf-8')))
f.write(']\n')
if (obfuscate):
f.write('''
checksum = '\''
{0}
'\''.replace('\\n', '')
'''.format(wrap(hexcode,120)))
mod_name_code = 'binascii.unhexlify(m[0]).decode(\'ascii\')'
mod_code = 'binascii.unhexlify(checksum)'
else:
mod_name_code = 'm[0]'
mod_code = '\'{0}\''.format(code)
f.write('''
import sys, shutil, os.path, types, binascii
try:
from builtins import bytes
except ImportError:
from future.builtins import bytes
for m in {0}:
x = {1}
module = types.ModuleType(x)
exec({2})
sys.modules[x] = module
del {0}, types, binascii
from pymolcas import main
from molcas_aux import which
f = which(sys.argv[0])
if (f is None):
f = sys.argv[0]
sys.exit(main(os.path.realpath(f)))
'''.format(mods_name, mod_name_code, mod_code))
except Exception as e:
print(str(e))
failed = True
if (failed):
os.remove(exe_name)
sys.exit(1)
else:
st = os.stat(exe_name)
os.chmod(exe_name, st.st_mode | stat.S_IEXEC)
sys.exit(0)
|