5th Chapter 4 "Monkeyrunner Source code Analysis" Monkey principle-start run: Command line argument resolution (original)

Source: Internet
Author: User

Heaven Zhuhai Branch Rudder note : Originally this series is to prepare a book, details please see the earlier blog "to seek partners to write the deep understanding of Monkeyrunner" books. But for many reasons, there is no wish. So the draft is shared here, so mistakes are unavoidable. If necessary, please refer to the following, the forwarding of the word also keep the end of each article source and other information.

After setting the monkey classpath environment variable to specify "/system/framework/framework/monkey.jar",/system/bin/monkey this shell script will pass App_ The process command Specifies Monkey's entry class "" Com.android.commands.monkey.Monkey "to find the main function to start running. There will be some initialization work to do before running, and one of the most important is to parse the command-line options and parameter values provided by the user.

Here is only the "Monkey-port 12345" as a scenario analysis of how the monkey is the command line parameter resolution, as for the other parameter parsing principle is the same, here do not parse, the following paste Monkey Help command printed out the help document, You can see which command line parameter options are supported by Monkey:

Figure 5-4-1 Monkey Support Command options

The "–port" option is to specify the ports that the monkey service needs to listen on, so that the client can connect to communicate with the monkey service.

Here we begin to analyze the source code of the Monkey application, first of all we first go to the main function of the Monkey class:

Code 5-4-1 Monkey-main

 414     /** 415 * Command-Line entry point. 416 * 417 * @param args the command-line arguments 418 */ 419      Public Static void Main(string[] args) {420         //Set The process name showing in "PS" or "Top" 421Process.setargv0 ("Com.android.commands.monkey");422         intResultCode = (NewMonkey ()). Run (args);423System.exit (ResultCode);424}

The key code 422 line first creates an instance of the Monkey class and then calls the run member method. This member method is relatively long, do a lot of things, down will slowly for you one by one Tao. One of the things you do is call the Processoptions method at the beginning to parse the command-line arguments.

Code 5-4-2 monkey-run Initialization command

 425     /** 426 * Run the command! 427 * 428 * @param args the command-line arguments 429 * @ Return Returns A posix-style result code. 0 for no error. 430 * * 431   Private int Run(string[] args) 432 {...//Omit initialization of some other member variables 444      This. Margs = args;445      This. Mnextarg =0;...//Omit initialization of some other member variables  the     if(!processoptions ()) {451       return-1;452}...//Other key methods will be analyzed in the next section, which is skipped first}

The No. 450 line of the code is done by some member variable initialization action, after the initialization will call 450 rows of processoptions for real command-line argument parsing and set the real command line from the member variable. Note that the No. 444 row saves the Margs member variable from the command line's array of arguments to the monkey instance, and then sets the Mnextarg cursor to 0 in line 445, which is used to iterate over the Margs command-line parameter array.

Code 5-4-3 monkey-processoptions

 632     /** 633 * Process the command-line options 634 * 635 * @return Returns True if options were PA Rsed with no apparent errors. 636 * * 637     Private Boolean processoptions() {            ...644String opt;645             while(opt = nextoption ())! =NULL)646                    if(Opt.equals ("-S")) {647                         This. MSeed = Nextoptionlong ("Seed");648}              ...//Omit similar processing code 713                Else if(Opt.equals ("--port")) {714                         This. Mserverport = ((int) Nextoptionlong ("Server port to listen in for commands"));715}                 ...//Omit similar processing code 742}            ...765     return true;766}

The code starts from 645 lines to 742 rows to execute a while loop, and each loop calls the Nextoption method to parse with a command-line parameter option, which corresponds to the method of taking the parameter value of the command line NEXTOPTIONXXX, etc. where xxx differs depending on whether the parameter value is a long integer or a string type:

    • Nextoptiondata Method : Represents the value of a string type to get the parameter value. For example, "Monkey-p Com.android.sample.notepad" limits the Application Package "Com.android.sample.notepad" in the range of application packages that monkey can manipulate is a string type

    • Nextoptionlong Method : Represents a value for which the parameter value is a numeric type, such as 12345 in "Monkey–port 12345".

For example, 713-714 line is to deal with Monkeyrunner start monkey command "Monkey-port 12345" passed the parameter "-port 12345" key, it determines if the parameter is "–port", You get the parameter value immediately following this parameter option, which is 12345, and then save it to the Monkey member variable mserverport for future use. Note that the parameters of the Nextoptionlong method here "Server port to listen in for commands" are really just debugging purposes.

Finally, let's look at how nextoption is going to get the next parameter option from the Margs array based on the current MNEXTARG array cursor, and how the corresponding Nextoptionlong gets the parameter value of the next parameter selection. Let's look at Nextoption first:

Code 5-4-4 monkey-nextoption

1117     PrivateStringnextoption() {1118         if(Mnextarg >= margs.length) {1119             return NULL;1120}1121String arg = Margs[mnextarg];1122         if(!arg.startswith ("-")) {1123             return NULL;1124}1125mnextarg++;1126         if(Arg.equals ("--")) {1127             return NULL;1128}1129         if(Arg.length () >1&& Arg.charat (1) !='-') {1130             if(Arg.length () >2) {1131Mcurargdata = arg.substring (2);1132                 returnArg.substring (0,2);1133}Else{1134Mcurargdata =NULL;1135                 returnArg1136}1137}1138Mcurargdata =NULL;1139         returnArg1140}

The Margs member variable is an array of type string, and from the analysis above in this section it is possible to know that the argument list passed in by the command line is stored inside. This code is relatively short and relatively simple. Before we analyze the command-line format supported by Monkey, let's make it easy to see what the code means:

    • –: Represents the Stop down processing option

    • -Z: Represents the command line option "-Z"

    • -Z ARGS: Represents the command-line option "-Z" and the option value is "ARGS", such as the "-S 100" command-line parameter option is specified to test the seed number of "-a", the value is the number of seeds 100

    • -zargs: Ditto, "-S 100" can also be written as "-s100"

    • –zz: Represents the command line option "-zz"

    • –zz args: Represents the command line option "-zz" and the option value is "ARGS"

After knowing the command-line format supported by monkey, it is still necessary to parse the member variables of several monkey classes used by the Nextoption method:

    • Margs: An array of command-line parameter options and values that the user has passed in.

    • Mnextarg: A cursor equivalent to an array that represents the current analysis to the first parameter.

    • mcurargdata: parameter value corresponding to a parameter option

The following is an analysis of this method, the main idea is to get a parameter from the Margs command line parameter array, and then through a series of judgments is legal, and finally if the legitimate words will be returned directly. In the analysis process, it is important to note that the whole method of doing things is to get the parameter options, not to get the parameter value, so do not be the parameter value args to affect your understanding, the args is obtained by other nextoptionxxx methods, For example, the next method that will be analyzed to get a long type of parameter value is Nextoptionlong, not here.

    • 1118-1120 row: No additional arguments are required to process, return NULL for invalid

    • 1121 rows: Get current parameter options for analysis based on current cursor

    • 1122-1124 rows: The parameter does not start with "-" and returns null for invalid

    • 1125 rows: Adjust cursor mnextarg, point to Parameter option/parameter value, specify parameter option or parameter value to see if the parameter is written "-zargs" form or "-Z ARGS" form. For example, "–port 12345–wait-dbg" for example, if the current need to analyze the "–port", then the execution of this line will be the cursor "12345" This parameter value. In the Nextoptionlong method that we need to analyze, we take the value out of the MNEXTARG cursor and point the cursor to the next line, the "–wait-dbg" option here, so that in the next netoption call, 1121 lines will be able to continue to remove the "–wait-dbg" this current option for a new round of analysis of

    • 1126-1128 lines: If "–", according to the previous parameter format description, representing the need to stop processing options, return NULL for invalid argument

    • Line 1129-1132: The case of "-zargs" is handled, the command line parameter options and parameter values are resolved simultaneously, the parameter value is stored in the monkey member variable mcurargdata inside, To get the command-line parameter value directly from the mcurargdata of monkey, such as Nextoptionlong, in the processoption while loop body, with the

    • 1134-1135 line: "- Z "and"-Z ARGS ", set the parameter value to NULL, So that methods such as Nextoptionlong can be called in the processoption while loop body to determine whether a parameter value needs to be parsed or the command line parameter values are obtained directly from Mcurargdata. Finally, in line 1135, the parameter option "-Z" returns to

    • 1138-1139 lines: The last processing is "-zz" and "-zz ARGS" option, the same way as above

Take the command "Monkey–port 12345" as an example. After obtaining the corresponding parameter options through the Nextoption method, such as "–port", then the need to do is to get the corresponding "12345" parameter option value. Here 12345 is considered to be a numeric value of a long integer, so the Nextoptionlong method is called.

Code 5-4-5 Monkey-nextoptionlong

1157     /**1158 * Returns a long converted from the next data argument with error handling1159 * If not available.1 *1161 * @param opt the name of the option.1162 * @return Returns a long converted Fro M The argument.1163 * *1164     Private Long Nextoptionlong(FinalString opt) {1165         LongResult1166         Try{1167result = Long.parselong (Nextoptiondata ());1168}Catch(NumberFormatException e) {1169System.err.println ("* * Error:"+ opt +" is not a number");1170             ThrowE1171}1172         returnResult1173}

Focus on 1167 lines, the String type command-line parameter value is obtained through the nextoptiondata call, and then the string is passed to grow the target value of the integer type by the Parselong method of long.

I don't know if you're in front of us. Nextoption analysis has not noticed that, when the parameter options and parameter values are merged together (such as-zargs), the method will be given the required parameter options (such as-Z) while the parameter value (ARGS) It is also analyzed and stored in the member variables of the Monkey class Mcurargdata member variables, and the parameter options and parameter values are separated (for example,-Z ARGS), the Nextoption method is only the parameter options to analyze, and set the Mcurargdata to null. In fact, the nextoptiondata we want to analyze is to obtain the parameter values of the corresponding parameter options according to these two conditions.

Code 5-4-6 Monkey-nextoptiondata

1141     /**1142 * Return the next data associated with the current option.1143 *1144 * @return Returns The data string, or null of there is no more arguments.1145 * /1146     PrivateStringNextoptiondata() {1147         if(Mcurargdata! =NULL) {1148             returnMcurargdata;1149}1150         if(Mnextarg >= margs.length) {1151             return NULL;1152}1153String data = Margs[mnextarg];1154mnextarg++;1155         returnData1156}

The main thing that this method does is, as previously stated, whether the member variable used to hold the parameter value is null (that is, whether the parameter value has been obtained by the way in the previous Nextoption method of getting the parameter option). Different ways to get the parameter values for the parameter options:

    • 1147-1149 line: First go to see mcurargdata this variable in the nextoption is not set to the actual parameter value, that is, 1147 rows to check whether Mcurargdata is null, If not, the parameter values are also analyzed in the nextoption analysis parameter option, so it is only necessary to return this value directly.

    • 1153 line: If Mcurargdata is null, the parameter value representing the corresponding parameter option has not been resolved, then use the nextoption already adjusted cursor Mnextarg above to get the corresponding parameter value from the command line parameter array Margs. It is then returned to the caller.

    • 1154 rows: Adjusts the cursor to the next parameter option in order to get the next option in the Parameter Options list Margs in the next nextoption for analysis. Or take the previous "Monkey–port 12345–wait-dbg" as an example, the previous nextoption obtained the "–port" This parameter option, and here the Nextoptiondata is the corresponding parameter value "12345" parse out, The cursor is then directed to the "–wait-dbg" option through the 1154 line of code.

    • 1155 rows: Returns the value of the parameter to the caller. In the above example, the "12345" listener port is returned to this section before the beginning of the analysis of the ProcessOption method, and then save the port to mserverport this member variable, the specific code to see the previous method of the analysis of 714 lines of code.

——— to Be Continued ———

Heaven Zhuhai Branch Rudder
Public Number: Techgogogo
Weibo: Http://weibo.com/techgogogo
Csdn:http://blog.csdn.net/zhubaitian

5th Chapter 4 "Monkeyrunner Source code Analysis" Monkey principle-start run: Command line argument resolution (original)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.