]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - scripts/finishSwigWrapperClasses.py
Vendor import of lldb release_39 branch r276489:
[FreeBSD/FreeBSD.git] / scripts / finishSwigWrapperClasses.py
1 """ Post process SWIG Bridge wrapper code Python script for Windows/LINUX/OSX platform
2
3     --------------------------------------------------------------------------
4     File:           finishSwigWrapperClasses.py
5
6     Overview:       Python script(s) to finish off the SWIG Python C++ Script
7                     Bridge wrapper code on the Windows/LINUX/OSX platform.
8                     The Python scripts are equivalent to the shell script (.sh)
9                     files.
10                     We use SWIG to create a C++ file containing the appropriate
11                     wrapper classes and functions for each scripting language,
12                     before liblldb is built (thus the C++ file can be compiled
13                     into liblldb.  In some cases, additional work may need to be
14                     done after liblldb has been compiled, to make the scripting
15                     language stuff fully functional.  Any such post-processing
16                     is handled through the Python scripts called here.
17
18     Gotchas:        None.
19
20     Copyright:      None.
21     --------------------------------------------------------------------------
22
23 """
24
25 # Python modules:
26 import sys      # Provide argument parsing
27 import os       # Provide directory and file handling
28
29 # Third party modules:
30
31 # In-house modules:
32 import utilsArgsParse   # Parse and validate this script's input arguments
33 import utilsOsType      # Determine the OS type this script is running on
34 import utilsDebug       # Debug Python scripts
35
36 # Instantiations:
37 gbDbgVerbose = False           # True = Turn on script function tracing, False = off.
38 gbDbgFlag = False              # Global debug mode flag, set by input parameter
39                                 # --dbgFlag. True = operate in debug mode.
40 gbMakeFileFlag = False         # True = yes called from makefile system, False = not.
41
42 # User facing text:
43 strMsgErrorNoMain = "Program called by another Python script not allowed"
44 strExitMsgSuccess = "Program successful"
45 strExitMsgError = "Program error: "
46 strParameter = "Parameter: "
47 strMsgErrorOsTypeUnknown = "Unable to determine OS type"
48 strScriptDirNotFound = "Unable to locate the script directory \'/script\'"
49 strScriptLangsFound = "Found the following script languages:"
50 strPostProcessError = "Executing \'%s\' post process script failed: "
51 strScriptNotFound = "Unable to locate the post process script file \'%s\' in \'%s\'"
52 strScriptLangFound = "Found \'%s\' build script."
53 strScriptLangsFound = "Found the following script languages:"
54 strExecuteMsg = "Executing \'%s\' build script..."
55 strExecuteError = "Executing \'%s\' build script failed: "
56 strHelpInfo = "\
57 Python script(s) to finish off the SWIG Python C++ Script \n\
58 Bridge wrapper code on the Windows/LINUX/OSX platform.  The Python \n\
59 scripts are equivalent to the shell script (.sh) files \n\
60 run on others platforms.\n\
61 Args:   -h              (optional) Print help information on this program.\n\
62     -d              (optional) Determines whether or not this script\n\
63                     outputs additional information when running.\n\
64     -m              (optional) Specify called from Makefile system.\n\
65     --srcRoot=          The root of the lldb source tree.\n\
66     --targetDir=            Where the lldb framework/shared library gets put.\n\
67     --cfgBldDir=            (optional) Where the build-swig-Python-LLDB.py program \n\
68                     will put the lldb.py file it generated from running\n\
69                     SWIG.\n\
70     --prefix=           (optional) Is the root directory used to determine where\n\
71                     third-party modules for scripting languages should\n\
72                     be installed. Where non-Darwin systems want to put\n\
73                     the .py and .so files so that Python can find them\n\
74                     automatically. Python install directory.\n\
75     --lldbLibDir    (optional) The name of the directory containing liblldb.so.\n\
76                     \"lib\" by default.\n\
77     --cmakeBuildConfiguration=  (optional) Is the build configuration(Debug, Release, RelWithDebugInfo)\n\
78                     used to determine where the bin and lib directories are \n\
79                     created for a Windows build.\n\
80     --argsFile=         The args are read from a file instead of the\n\
81                     command line. Other command line args are ignored.\n\
82 \n\
83 Usage:\n\
84     finishSwigWrapperClasses.py --srcRoot=ADirPath --targetDir=ADirPath\n\
85     --cfgBldDir=ADirPath --prefix=ADirPath --lldbLibDir=ADirPath -m -d\n\
86 \n\
87 " #TAG_PROGRAM_HELP_INFO
88
89 #++---------------------------------------------------------------------------
90 # Details:  Exit the program on success. Called on program successfully done
91 #           its work. Returns a status result to the caller.
92 # Args:     vnResult    - (R) 0 or greater indicating success.
93 #           vMsg        - (R) Success message if any to show success to user.
94 # Returns:  None.
95 # Throws:   None.
96 #--
97 def program_exit_success(vnResult, vMsg):
98     strMsg = ""
99
100     if vMsg.__len__() != 0:
101         strMsg = "%s: %s (%d)" % (strExitMsgSuccess, vMsg, vnResult)
102         print(strMsg)
103
104     sys.exit(vnResult)
105
106 #++---------------------------------------------------------------------------
107 # Details:  Exit the program with error. Called on exit program failed its
108 #           task. Returns a status result to the caller.
109 # Args:     vnResult    - (R) A negative number indicating error condition.
110 #           vMsg        - (R) Error message to show to user.
111 # Returns:  None.
112 # Throws:   None.
113 #--
114 def program_exit_on_failure(vnResult, vMsg):
115     print(("%s%s (%d)" % (strExitMsgError, vMsg, vnResult)))
116     sys.exit(vnResult)
117
118 #++---------------------------------------------------------------------------
119 # Details:  Exit the program return a exit result number and print a message.
120 #           Positive numbers and zero are returned for success other error
121 #           occurred.
122 # Args:     vnResult    - (R) A -ve (an error), 0 or +ve number (ok or status).
123 #           vMsg        - (R) Error message to show to user.
124 # Returns:  None.
125 # Throws:   None.
126 #--
127 def program_exit(vnResult, vMsg):
128     if vnResult >= 0:
129         program_exit_success(vnResult, vMsg)
130     else:
131         program_exit_on_failure(vnResult, vMsg)
132
133 #++---------------------------------------------------------------------------
134 # Details:  Dump input parameters.
135 # Args:     vDictArgs   - (R) Map of input args to value.
136 # Returns:  None.
137 # Throws:   None.
138 #--
139 def print_out_input_parameters(vDictArgs):
140     for arg, val in list(vDictArgs.items()):
141         strEqs = ""
142         strQ = ""
143         if val.__len__() != 0:
144             strEqs = " ="
145             strQ = "\""
146         print(("%s%s%s %s%s%s\n" % (strParameter, arg, strEqs, strQ, val, strQ)))
147
148 #++---------------------------------------------------------------------------
149 # Details:  Validate the arguments passed to the program. This function exits
150 #           the program should error with the arguments be found.
151 # Args:     vArgv   - (R) List of arguments and values.
152 # Returns:  Int     - 0 = success, -ve = some failure.
153 #           Dict    - Map of arguments names to argument values
154 # Throws:   None.
155 #--
156 def validate_arguments(vArgv):
157     dbg = utilsDebug.CDebugFnVerbose("validate_arguments()")
158     strMsg = ""
159     dictArgs = {}
160     nResult = 0
161     strListArgs = "hdm" # Format "hiox:" = -h -i -o -x <arg>
162     listLongArgs = ["srcRoot=", "targetDir=", "cfgBldDir=", "prefix=", "cmakeBuildConfiguration=",
163                     "lldbLibDir=", "argsFile"]
164     dictArgReq = {  "-h": "o",          # o = optional, m = mandatory
165                     "-d": "o",
166                     "-m": "o",
167                     "--srcRoot": "m",
168                     "--targetDir": "m",
169                     "--cfgBldDir": "o",
170                     "--prefix": "o",
171                     "--cmakeBuildConfiguration": "o",
172                     "--lldbLibDir": "o",
173                     "--argsFile": "o" }
174
175     # Check for mandatory parameters
176     nResult, dictArgs, strMsg = utilsArgsParse.parse(vArgv, strListArgs,
177                                                      listLongArgs,
178                                                      dictArgReq,
179                                                      strHelpInfo)
180     if nResult < 0:
181         program_exit_on_failure(nResult, strMsg)
182
183     # User input -h for help
184     if nResult == 1:
185         program_exit_success(0, strMsg)
186
187     return (nResult, dictArgs)
188
189 #++---------------------------------------------------------------------------
190 # Details:  Locate post process script language directory and the script within
191 #           and execute.
192 # Args:     vStrScriptLang      - (R) Name of the script language to build.
193 #           vstrFinishFileName  - (R) Prefix file name to build full name.
194 #           vDictArgs           - (R) Program input parameters.
195 # Returns:  Int     - 0 = Success, < 0 some error condition.
196 #           Str     - Error message.
197 # Throws:   None.
198 #--
199 def run_post_process(vStrScriptLang, vstrFinishFileName, vDictArgs):
200     dbg = utilsDebug.CDebugFnVerbose("run_post_process()")
201     nResult = 0
202     strStatusMsg = ""
203     strScriptFile = vstrFinishFileName % vStrScriptLang
204     strScriptFileDir = os.path.normpath(os.path.join(vDictArgs["--srcRoot"], "scripts", vStrScriptLang))
205     strScriptFilePath = os.path.join(strScriptFileDir, strScriptFile)
206
207     # Check for the existence of the script file
208     strPath = os.path.normcase(strScriptFilePath)
209     bOk = os.path.exists(strPath)
210     if bOk == False:
211         strDir = os.path.normcase(strScriptFileDir)
212         strStatusMsg = strScriptNotFound % (strScriptFile, strDir)
213         return (-9, strStatusMsg)
214
215     if gbDbgFlag:
216         print((strScriptLangFound % vStrScriptLang))
217         print((strExecuteMsg % vStrScriptLang))
218
219     # Change where Python looks for our modules
220     strDir = os.path.normcase(strScriptFileDir)
221     sys.path.append(strDir)
222
223     # Execute the specific language script
224     dictArgs = vDictArgs # Remove any args not required before passing on
225     strModuleName = strScriptFile[: strScriptFile.__len__() - 3]
226     module = __import__(strModuleName)
227     nResult, strStatusMsg = module.main(dictArgs)
228
229     # Revert sys path
230     sys.path.remove(strDir)
231
232     return (nResult, strStatusMsg)
233
234 #++---------------------------------------------------------------------------
235 # Details:  Step through each script language sub directory supported
236 #           and execute post processing script for each scripting language,
237 #           make sure the build script for that language exists.
238 #           For now the only language we support is Python, but we expect this
239 #           to change.
240 # Args:     vDictArgs   - (R) Program input parameters.
241 # Returns:  Int     - 0 = Success, < 0 some error condition.
242 #           Str     - Error message.
243 # Throws:   None.
244 #--
245 def run_post_process_for_each_script_supported(vDictArgs):
246     dbg = utilsDebug.CDebugFnVerbose("run_post_process_for_each_script_supported()")
247     nResult = 0
248     strStatusMsg = ""
249     strScriptDir = os.path.normpath(os.path.join(vDictArgs["--srcRoot"], "scripts"))
250     strFinishFileName = "finishSwig%sLLDB.py"
251
252     # Check for the existence of the scripts folder
253     strScriptsDir = os.path.normcase(strScriptDir)
254     bOk = os.path.exists(strScriptsDir)
255     if bOk == False:
256         return (-8, strScriptDirNotFound)
257
258     # Look for any script language directories to build for
259     listDirs = ["Python"]
260
261     # Iterate script directory find any script language directories
262     for scriptLang in listDirs:
263         # __pycache__ is a magic directory in Python 3 that holds .pyc files
264         if scriptLang != "__pycache__" and scriptLang != "swig_bot_lib":
265             dbg.dump_text("Executing language script for \'%s\'" % scriptLang)
266             nResult, strStatusMsg = run_post_process(scriptLang, strFinishFileName,
267                                                      vDictArgs)
268         if nResult < 0:
269             break
270
271     if nResult < 0:
272         strTmp = strPostProcessError % scriptLang
273         strTmp += strStatusMsg
274         strStatusMsg = strTmp
275
276     return (nResult, strStatusMsg)
277
278 #++---------------------------------------------------------------------------
279 # Details:  Program's main() with arguments passed in from the command line.
280 #           Program either exits normally or with error from this function -
281 #           top most level function.
282 # Args:     vArgv   - (R) List of arguments and values.
283 # Returns:  None
284 # Throws:   None.
285 #--
286 def main(vArgv):
287     dbg = utilsDebug.CDebugFnVerbose("main()")
288     bOk = False
289     dictArgs = {}
290     nResult = 0
291     strMsg = ""
292
293     # The validate arguments fn will exit the program if tests fail
294     nResult, dictArgs = validate_arguments(vArgv)
295
296     eOSType = utilsOsType.determine_os_type()
297     if eOSType == utilsOsType.EnumOsType.Unknown:
298         program_exit(-4, strMsgErrorOsTypeUnknown)
299
300     global gbDbgFlag
301     gbDbgFlag = "-d" in dictArgs
302     if gbDbgFlag:
303         print_out_input_parameters(dictArgs)
304
305     # Check to see if we were called from the Makefile system. If we were, check
306     # if the caller wants SWIG to generate a dependency file.
307     # Not used in this program, but passed through to the language script file
308     # called by this program
309     global gbMakeFileFlag
310     gbMakeFileFlag = "-m" in dictArgs
311
312     nResult, strMsg = run_post_process_for_each_script_supported(dictArgs)
313
314     program_exit(nResult, strMsg)
315
316 #-----------------------------------------------------------------------------
317 #-----------------------------------------------------------------------------
318 #-----------------------------------------------------------------------------
319
320 #TAG_PROGRAM_HELP_INFO
321 """ Details: Program main entry point.
322
323     --------------------------------------------------------------------------
324     Args:   -h (optional)   Print help information on this program.
325             -d (optional)   Determines whether or not this script
326                             outputs additional information when running.
327             -m (optional)   Specify called from Makefile system. If given locate
328                             the LLDBWrapPython.cpp in --srcRoot/source folder
329                             else in the --targetDir folder.
330             --srcRoot=      The root of the lldb source tree.
331             --targetDir=    Where the lldb framework/shared library gets put.
332             --cfgBldDir=    Where the buildSwigPythonLLDB.py program will
333             (optional)      put the lldb.py file it generated from running
334                             SWIG.
335             --prefix=       Is the root directory used to determine where
336             (optional)      third-party modules for scripting languages should
337                             be installed. Where non-Darwin systems want to put
338                             the .py and .so files so that Python can find them
339                             automatically. Python install directory.
340             --cmakeBuildConfiguration=  (optional) Is the build configuration(Debug, Release, RelWithDebugInfo)\n\
341                             used to determine where the bin and lib directories are \n\
342                             created for a Windows build.\n\
343             --lldbLibDir=   The name of the directory containing liblldb.so.
344             (optional)      "lib" by default.
345             --argsFile=     The args are read from a file instead of the
346                             command line. Other command line args are ignored.
347     Usage:
348             finishSwigWrapperClasses.py --srcRoot=ADirPath --targetDir=ADirPath
349             --cfgBldDir=ADirPath --prefix=ADirPath --lldbLibDir=ADirPath -m -d
350
351     Results:    0 Success
352                 -1 Error - invalid parameters passed.
353                 -2 Error - incorrect number of mandatory parameters passed.
354
355                 -4 Error - unable to determine OS type.
356                 -5 Error - program not run with name of "__main__".
357                 -8 Error - unable to locate the scripts folder.
358                 -9 Error - unable to locate the post process language script
359                            file.
360
361                 -100+    - Error messages from the child language script file.
362
363     --------------------------------------------------------------------------
364
365 """
366
367 # Called using "__main__" when not imported i.e. from the command line
368 if __name__ == "__main__":
369     utilsDebug.CDebugFnVerbose.bVerboseOn = gbDbgVerbose
370     dbg = utilsDebug.CDebugFnVerbose("__main__")
371     main(sys.argv[1:])
372 else:
373     program_exit(-5, strMsgErrorNoMain)