关于Files‘ name is invalid or does not exist的解决方法

14 篇文章 0 订阅

在使用SmartUpload做上传时,总是报错:Files' name is invalid or does not exist


LZ用尽所有的搜索,得到的结果几乎全是关于form标签的enctype属性

可是既然做上传功能,大家基本上都知道配置这个属性

最后LZ发现<input type="file" name=""/>标签的name属性必须有才不会报错


LZ的一点小小经验,分享给遇到此问题的童鞋

【2013-12-01涨姿势】:在上传文件的时候要注意html的file标签也要给name赋值,否则post上去后,服务器端是找不到file对象的



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
PassMark BurnInTest V5.3 Copyright (C) 1999-2008 PassMark Software All Rights Reserved http://www.passmark.com Overview ======== Passmark's BurnInTest is a software tool that allows all the major sub-systems of a computer to be simultaneously tested for reliability and stability. Status ====== This is a shareware program. This means that you need to buy it if you would like to continue using it after the evaluation period. Installation ============ 1) Uninstall any previous version of BurnInTest 2) Double click (or Open) the downloaded ".exe" file 3) Follow the prompts UnInstallation ============== Use the Windows control panel, Add / Remove Programs Requirements ============ - Operating System: Windows 2000, XP, 2003 server, Vista (*) - RAM: 32 Meg - Disk space: 6 Meg of free hard disk space (plus an additional 10Meg to run the Disk test) - DirectX 9.0c or above software for 3D graphics and video tests (plus working DirectX drivers for your video card) - SSE compatible CPU for SSE tests - A printer to run the printer test, set-up as the default printer in Windows. - A CD ROM + 1 Music CD or Data CD to run the CD test. - A CD-RW to run the CD burn test. - A network connection and the TCP/IP networking software installed for the Network Tests Pro version only: - A serial port loop back plug for the serial port test. - A parallel port loop back plug for the parallel port test. - A USB port loop back plug for the USB port test. - A USB 2.0 port loop back plug for the USB 2.0 port test. - PassMark ModemTest V1.3 1010 (or higher) for Plugin Modem testing. - PassMark KeyboardTest V2.2 1011 (or higher) for Plugin Keyboard testing. - PassMark Firewire Plugin V1.0 1000 (or higher) and a 揔anguru FireFlash?drive for Plugin Firewire testing. (*) Windows 2000 does not support the CD-RW burn test. The advanced RAM test is only available under Windows 2000 and Windows XP professional (the other RAM tests are supported under the other OS's). Users must have administrator privileges. Windows 98 and Windows ME ========================= Windows 98 and ME are not supported in BurnInTest version 5.3 and above. Use a version of BurnInTest prior to 5.2 for compatibility with W98 and ME. Windows 95 and Windows NT ========================= Windows 95 and NT are not supported in BurnInTest version 4.0 and above. Use a version of BurnInTest prior to 3.1 for compatibility with W95 and NT. Version History =============== Here is a summary of all changes that have been made in each version of BurnInTest. Release 5.3 build 1035 revision 4 WIN32 release 10 November 2008 - Lenovo China specific build. Lenovo system detection changes. Release 5.3 build 1035 revision 3 WIN32 release 7 November 2008 - Lenovo China specific build. Lenovo system detection changes. Release 5.3 build 1035 revision 2 WIN32 release 6 November 2008 - Lenovo China specific build. Lenovo logo and Lenovo system detection changes. Release 5.3 build 1035 WIN32 release 5 November 2008 - Lenovo China specific build. Changes include: Lenovo logo added, Lenovo system support only, 32-bit BurnInTest restricted to 32-bit Windows and BurnInTest run as administrator. Release 5.3 build 1034 WIN32 release 3 October 2008 - Correction to setting the CD burn test drive in preferences. - Changed the mechanism to check for the required DirectX Direct3D as the previous method did not work on some system (some W2003 servers). - Enhanced the mechanism to report memory hardware errors in the Memory torture test. Release 5.3 build 1033 WIN32 release 1 October 2008 - Changes to correct a BurnInTest crash problem on some systems. When the disk and standard RAM tests are run for many hours, BurnInTest may have disappeared with no error message. Release 5.3 build 1030 WIN32 release 25 September 2008 - Changes to investigate a BurnInTest crash problem on XP SP3. Release 5.3 build 1028 WIN32 release 11 September 2008 - Two 2D Video memory test crash bug workarounds implemented. Crashes in (i) DirectX DirectShow and (ii) ATI atiumdag.dll library. - A hang on startup has been corrected. A 2 minute timeout has been added to the collection of system information. - Video playback, Hard disk and CD/DVD test 'no operations' error reporting changed. - When BurnInTest crashes, it will not generate a "minidump" file. Minidumps will need to be sent to Microsoft as per the normal process. However, a log entry will be added to the normal BurnInTest log. - Changes to trace logging to reduce activity when trace logging is not turned on. - Note: We have seen a report of the Video Playback failing (crash) due to a faulty video codec, ffdshow.ax. If you are using this we suggest you try a different Video file and codec. Release 5.3 build 1027 revision 0003 WIN32 release 19 August 2008 - Changed the 2D test to wait for the Video Playback test in order to allow memory allocation for the Video playback test. - Changed the Memory test to wait for the Video Playback test and 3D test to allow memory allocation for these tests. - Minor changes to the No operation error watchdog timer for the CD and Hard disk tests. - Minor correction to the Butterfly seek test. - Video playback trace logging increased. Release 5.3 build 1027 revision 0002 WIN32 release 19 August 2008 - Video playback trace logging increased. Release 5.3 build 1027 WIN32 release 31 July 2008 - Corrected a bug where BurnInTest would fail to start if Activity trace level 2 logging (debug level logging) was turned on and the Logging Summarize option was also selected. - Minor change to the serial port test where, if "Disable RTS/CTS and DSR/DTR test phase" was selected the DTR and RTS lines would be explicitly disabled to prevent any toggling of these lines. Previously these where enabled, but not explicitly toggled. Release 5.3 build 1026 WIN32 release 17 July 2008 - Updated Level 2 and Level 3 CPU cache information for newer Intel CPU's. - Updated the detection of Hyperthreading and the number of logical CPUs for a new Intel CPU. Release 5.3 build 1025 WIN32 release 11 July 2008 - Corrected a Disk test bug where on rare occasions a verification error is incorrectly displayed. This is during the random seeking phase of the "Random data with random seeking" test mode and only occurs with some specific test settings. Release 5.3 build 1024 WIN32 release 10 July 2008 - Workaround for the rare crash bug in Vista in atklumdisp.dll at address 0x730676ae. - Added trace debug information for BurnInTest startup and the 3D test. Release 5.3 build 1022 WIN32 release 12 June 2008 - Corrected a bug where the 2D video memory test in BurnInTest v5.3.1020 and v5.3.1021 would report a "Not enough video memory available for test" error if the test was run a couple of times (without closing BurnInTest). Release 5.3 build 1021 WIN32 release 5 June 2008 - 32-bit BurnInTest PRO 5.3.1020 would not start on Windows 2000. This has been corrected. Release 5.3 build 1020 WIN32 release 29 May 2008 - BurnInTest could have crashed on accessing bad video memory hardware in the 2D test. This problem is now just reported as an error (and BurnInTest) continues. - When BurnInTest crashes, it should now generate a "minidump" file to help debug which system component caused the failure (32-bit Pro version only). - Other minor changes. Release 5.3 build 1019 WIN32 release 16 May 2008 - Corrected rare crash bugs in the 2D and Video tests. - Added a hot Key, F4, to set the auto run flag and run the tests (i.e. set "-r" and then run the tests). - Other minor changes. Release 5.3 build 1018 WIN32 release 16 April 2008 - Added an operation watchdog timer for all tests. In rare cases, a single test can stop in the operating system - i.e. there is a problem in the operating system/ device driver that prevents control being returned to the BurnInTest for that test. This was added for specialized serial port hardware that could lockup after several hours of testing. Release 5.3 build 1017 WIN32 release 3 April 2008 - Corrected the Advanced Network test to run on non-English Operating Systems. Release 5.3 build 1016 WIN32 release 17 March 2008 - Added additional USB 2.0 Loopback plug test initialization to ensure plugs are in a 'clean' state when starting the USB tests. This was added due to reported USB data verification errors after scripted USB testing across multiple reboots. Release 5.3 build 1015 WIN32 release 27 February 2008 - Increased error reporting detail for the standard RAM test, when the -v command line option is used. Release 5.3 build 1014 WIN32 release 30 January 2008 - Corrected a problem where the loopback sound test could run out of memory if run for several days. Release 5.3 build 1013 WIN32 release 31 December 2007 - Improved the reporting of COM port errors such that in the rare case a COM port locks up in the Operating System, the error is still reported. - Corrected a bug, where in rare cases, the result summary could be duplicated in a log file. - Updated license management, in an attempt to remove a rare crash on startup. Release 5.3 build 1012.0002 WIN32 release 31 October 2007 - New build of Rebooter (64-bit Windows correction). - Clarifications in the help file. Release 5.3 build 1012 WIN32 release 17 October 2007 - Changed the Standard Network Test, "Test all available NICs" such that the number of Network Addresses specified in Preferences->Network will be the number of NICs tested. This will error faulty NICs that are not detected by the BurnInTest auto NIC detection mechanism. - Minor change to the 2D memory test when run with the 3D test (multiple large windows) and the RAM test. Aimed at correcting sympton: Access Violation 0x00404CF9. - Corrections to the mapping of paths with ".\". Release 5.3 build 1011 rev 2 WIN32 release 17 September 2007 - Modified the Multi-Process torture test to better describe a new error message introduced in V5.3.1010. Release 5.3 build 1011 - Public release WIN32 release 11 September 2007 - Corrected a bug where "Limited Evaluation Version" could be displayed even after BUrnInTest is licensed (problem introduced in 32-bit BITPRO V5.3.1010). - Changed the Sound test to allow any of the tests (Wave, Midi or MP3) to be excluded from testing by blanking the filename. - The Command line parameter "-j" (cycle disk test patterns after each test file) could fail during the Random data test due to the mechanism used in BurnInTest. The Random data test is now excluded from the test when (and only when) the "-j" command line parameter is specified. - In rare circumstances, the 2D test number of operations could potentially overflow and become negative. This has been corrected. - In rare circumstances, BurnInTest could hang if there was a system problem in rebooting the system (ie. it failed to shutdown) using PassMark Rebooter. This has been corrected. Release 5.3 build 1010 - Public release WIN32 release 28 August 2007 WIN64 release 28 August 2007 - As BurnInTest exercises system components, it is possible for faulty hardware or device drivers to cause software exceptions. These are normally seen as Windows reporting an "Access Violation". Changes have been made to handle these errors for the memory tests (for faulty RAM) and direct device driver access (for some device driver errors), as well as overarching more generic handling of these types of errors. - Corrected a software failure bug on startup (particularly Vista) where a DirectX function was causing software failures in "dsetup.dll". - Updated the "Activity Event" generated with the periodic results summary report to be numbered (from 1 upwards) such that when "Logging->Summarize", these events are not summarized. - Corrected a bug where the HTML log name could include a duplicate of the filename prefix. - Updated to the Common Errors section of help. Release 5.3 build 1009 - Public release WIN32 release 16 August 2007 - Corrected a 'zip' version cleanup problem. Release 5.3 build 1008 - Komputer Swiat Expert magazine version WIN32 STD release 14 August 2007 Release 5.3 build 1007 - Public release WIN32 release 7 August 2007 - Corrected a disk test startup problem for some large RAID systems when SMART testing is selected. - Added additional logging for the disk test when an error occurs. - Changed the 3D test when run with the 2D EMC test to be 'behind' the EMC scrolling H's test. Allowed the test to be easily exited when running the 3D test in Fullscreen mode. - Minor corrections to the Advanced Network test. - Changed the log file reference of "Network Name" to "Computer Name". WIN64 specific: - MMX and 3DNow! are obsolete for native 64-bit applications. BurnInTest has been changed to show "NA" (Not applicable) in the test window for these tests. Release 5.3 build 1006 - Limited release WIN32 release 17 July 2007 - Standard Network Test changes: - Increased the number of destination IP addresses from 4 to 6. - Added an option (default) "Test all available NICs", which will force traffic down every system NIC with a basic algorithm of NIC1 to IP Address 1, NIC2 to IP Address 2 etc. - Advanced Network test changes: - Simplified the test. - Removed the UDP and FTP options. The Standard Network test can be used as a UDP test. - Removed the Advanced Network test specific logging, and included all relevant logging in the standard BurnInTest logging mechanism. - Replaced the complicated dynamic balancing of any system NIC to any Endpoint NIC with a simpler static allocation on test startup. - Changed the error detection mechanism to detect errors much more quickly. - Re-worked the errors reported. - Changed the CPU throttling mechanism to reduce the CPU load. - Updated endpoint.exe. - Removed checkend.exe (now obsolete). - Changed the logging rollover to work with the output of interim results (e.g. per 1 minute). Previously rollover only occurred on error events written to the log. This also corrected an issue where interim results summary logging could be written to the physical disk with some delay (based on Windows disk caching). - Corrected the "Unknown" reporting of some operating systems. - Added the skipping of the Butterfly seek disk test when run on Vista and insufficient privileges. A notification of this is logged. - Intel Quad core L2 cache size reporting has been added. - Added new SMART threshold descriptions. - Added new disk test options, accessed via command line parameters: /ka: keep disk test files in all cases (c.f. /k keep disk test files on error). /j: cycle patterns between test files. Note: Random seeking will be skipped in this case. This option has been added to allow multiple test patterns to be used across very large disks. - Added an option to make some test settings unavailable to the user. An example configuration file available on request. Release 5.3 build 1005 0001 (STD only) - Public release WIN32 release 29 June 2007 - Corrected a bug introduced in v5.3.1005.0000 STD (only) where the disk test would use up more and more system resources, thus causing test failures. Release 5.3 build 1005 rev 0003 (PRO only) - Limited public release WIN32 release 21 June 2007 - Correction to the behavior of a static RAM test pattern (rather than the default Cyclic pattern). Release 5.3 build 1005 rev 0002 (PRO only) - Limited public release WIN32 release 15 June 2007 - The "Select all CD/DVD drives" preferences option has been made user configurable, rather than using pre-defined test settings. Release 5.3 build 1005 rev 0001 (PRO only) - Limited public release WIN32 release 13 June 2007 - Bug correction for the CD auto selection feature. Release 5.3 build 1005 - Public release WIN32 release 18 May 2007 WIN64 release 18 May 2007 - In a number of cases, such as when specifying the post test application, uppercase application names were not accepted. This has been corrected. - The default font height in the 2D scrolling H's test should have been Arial 9. This has been changed. - The BurnInTest Video playback test incompatibility with Nero 6 and Nero 7 has been resolved. - The BurnInTest disk test throughput for dual core systems has been improved. Release 5.3 build 1004 rev2 - Limited release WIN32 release 8 May 2007 - Changed the Standard Network Test to better report packet error ratios. In addition, a new warning has been added to indicate that errors have been detected but not enough packets have been attempted to be sent to determine accurately whether the configured error ratio has been exceeded. - Corrected a bug where the "append to existing" logging option did not work across scripted reboots, and a new log file was created instead of appending to the existing log file. - If the 3D test was running, then BurnInTest blocked a forced close of BurnInTest, this blocking has been removed. - Changed the PASS and FAIL windows so they can now also be closed by selecting the Windows Close "X" button. Release 5.3 build 1004 - Public release WIN32 release 10 April 2007 WIN64 release 10 April 2007 - Corrected a problem introduced in BurnInTest v5.2 where BurnInTest could run out of memory (the main symptom) when tests where run for long periods (> 12hours). WIN64 specific: - Corrected a bug where the number of cores reported on a Quad core system was incorrectly reported as CPU packages. Release 5.3 build 1003 - Limited release WIN32 release 3 April 2007 - A new 2D GUI (Graphical User Interface) test has been added to the standard 2D graphics test. - Resolved an issue where BurnInTest would fail to start on Vista systems with DEP enabled for all programs. - On some systems, the Disk test could pause momentarily even when a duty cycle of 100% was specified. This pause has been removed. - When running the CD test under BartPE (Pre-install environment) 4 additional specific files are skipped as they are unavailable for testing. - Minor bug corrections. Release 5.3 build 1002 rev 0001 - Limited release WIN32 release 16 March 2007 - Changes to the new 3D test: - Added a Full screen non-windowed test for the primary monitor, where the resolution can be selected from those supported by the Graphics card. - Added the user option of changes the vertical sync in the full screen non-windowed test to be either the Maximum rate of the graphics card, or to be the rate of the monitor (this may prevent some flicker). - Added a more complex water texture using DirectX Vertex Shader 2.0 and Pixel Shader 2.0 effects (if supported by the graphics card). This applies to 3D test windows that are 800x600 or larger. - Changed some error messages from window displays (that require user intervention) to standard error reporting. Added new 3D error messages and more detail in the error reporting. - Changed the definition of an operation to be a successfully displayed frame. - Changed the definition of a cycle to be 2000 frames. - Changed 2D video memory test to wait until the 3D test starts (as per V5.2 and earlier). - A new version of rebooter has been included. - If BurnInTest is started with the -p command line parameter (to use the bit.exe directory for files such as the configuration file), then BurnInTest will start rebooter with the -p option. This can be useful when running BurnInTest and Rebooter from a USB drive. Release 5.3 build 1002 - Limited release WIN32 release 19 March 2007 - Corrected a bug introduced in V5.2 where selecting accumulated logging could lead to rebooter failing to launch. Release 5.3 build 1001 - Limited release WIN32 release 16 March 2007 - The 3D test has been improved. The 3D ball test has been replaced with a more complex 3D terrain test. This will more thoroughly exercise modern graphics cards. Further, the 3D test has been changed to support multi- monitor testing (up to 4 monitors). Accordingly, a new preferences section has been added for the 3D test. The multi-monitor test options are only available in BurnInTest Professional. Release 5.3 build 1001 - Limited release WIN32 release 16 March 2007 - The 3D test has been improved. The 3D ball test has been replaced with a more complex 3D terrain test. This will more thoroughly exercise modern graphics cards. Further, the 3D test has been changed to support multi- monitor testing (up to 4 monitors). Accordingly, a new preferences section has been added for the 3D test. The multi-monitor test options are only available in BurnInTest Professional. - BurnInTest uses DirectX 9.0c. This version of BurnInTest uses a more recent version of the Microsoft DirectX Direct3D component, October 2006. BurnInTest has been modified to detect and install this component (file) if it does not exist. - A command line parameter -X has been added to skip the DirectX version checking on BurnInTest start-up. - With the recent introduction of multi-monitor support for the Video Playback test, it is now more likely that the system will run out of memory when running multiple video tests simultaneously, particularly when more memory intensive codecs are used. A specific Insufficient resources to complete test message has been added in this case, rather than the previous more generic unrecoverable error message. The video test have been changed to attempt recovery from this and the more generic unrecoverable error, by closing the current video and opening the next. The logging detail has been increased. - Note: The BurnIntest sample video pack has been altered with the DivX Compressed Video file being removed due to the DivX codec failing with this Video file when used with multiple simultaneous Video playbacks. Access Violation: 0x69756e65. See: http://www.passmark.com/download/bit_download.htm - The video description is now collected for a larger range of Vista systems. - Windows 98 and ME are no longer supported. Please see www.passmark.com for a link to an older version of BurnInTest that will support W98/ME. Release 5.3 build 1000 rev2 - Limited release WIN32 release 9 March 2007 - A command line parameter -P has been added to allow the BurnInTest directory to be used rather than the User's personal directory. This may be useful when running BurnInTest from a USB drive for example. - When running the CD test under BartPE (Pre-install environment) 4 additional specific files are skipped as they are unavailable for testing. - A change has been made to support Hmonitor temperature monitoring on Vista. - A number of undocumented command line parameters have been documented: -B: BurnInTest will generate additional Serial port test information when activity trace level 2 logging is set. -E [data]: Specifies the test data to use in the serial port test. -M: Automatically display the Machine ID Window when BurnInTest is started. -U: Force BurnInTest to set logging on at startup. Release 5.3 build 1000 - Limited release WIN32 release 8 March 2007 - Changed the 2D and Video playback tests to support multi-monitor testing. - When running the CD test under BartPE (Pre-install environment) 4 specific files are skipped as they are unavailable for testing. Release 5.2 build 1006 - Limited release WIN32 release 1 March 2007 - Corrected a bug where BurnInTest would fail to start on certain Vista systems. - Corrected a bug where some files where the full path was not specified would be incorrectly referenced in the Program Files directory, rather than the user personal directory. Release 5.2 build 1005 - Public release WIN32 release 21 February 2007 WIN64 release 21 February 2007 - Updated the Graphics card description for Windows Vista systems. - Updated the Advanced Network test to indicate that elevated administrator privileges are required when running on Vista. - Moved files from the Program files directory for the Advanced Network Test (BurnInTest, EndPoint and CheckEnd). Specifically, the User Application directory is now used for the temporary test FTP files and the User Personal directory is now used for the log and configuration files. - Updated the cleanup process for when running the "zip" version of BurnInTest Professional from a CD or flash drive. - Updated the help link from the Windows Start, All Programs, BurnInTest menu for the browser based help. - Corrected a bug where Disk preferences displayed in the Preferences window would be incorrect when the system had no Floppy drive. - Corrected a bug where the Advanced Network test might not have been displayed until after entering the Duty Cycle selection (ie. just chaning from the standard network test to the advanced test). - Corrected a USB bug in Beta 5.2.1003 where the test would not run if there where there insufficient USB loopback plugs attached to the system. - Included a new version of PassMark Rebooter that supports Windows Vista. Release 5.2 build 1004 - Public Pre-release WIN32 release 13 February 2007 - Updated the reported Operating system for the various Vista product editions. - Disk test settings can be configured for "Automatically Select all Hard Disks", rather than using defaults. - When running the CD test under BartPE (Pre-install environment) 4 specific files are skipped as they are unavailable for testing. - Corrected a bug where temperature information could be duplicated in the HTML report. - Corrected a bug certain 'save report' warning messages could be truncated. - Help file updated. Release 5.2 build 1003 - BETA RELEASE ONLY WIN32 release 23 January 2007 - Changed the USB preferences and test to more completely check for the PassMark USB Loopback plugs and ignore any device that is not a PassMark USB Loopback plug (due to reported incorrect detection with another hardware device). - Increased Trace level debugging for Intel temperature monitoring. - Corrected a bug with the disk test introduced in 5.2.1001 Release 5.2 build 1002 - BETA RELEASE ONLY WIN32 release 22 January 2007 - Increased the number of disks that can be tested from 20 to 26. - Updated BurnInTest to reflect that Temperature monitoring with Intel Desktop utilities is supported. Intel Desktop utilities essentially is a replacement for Intel Active Monitor for newer Intel motherboards. - Increased Trace level debugging for Intel temperature monitoring. Release 5.2 build 1001 - BETA RELEASE ONLY WIN32 release 19 January 2007 - Windows Vista support. - The Block size used in the disk test is now configurable per disk. The default block size has been increased from 16KB to 32KB. - An option has been added to automatically detect all of the CD and DVD drives for the CD test (as per the disk test). This may be useful when testing across many systems with different optical drive configurations. - Increased Trace level debugging for Intel temperature monitoring. - Bugs corrected: - Disk preferences - in rare cases invalid default values could be set for a disk, an invalid value error would occur and the values would need to be manually corrected. Release 5.2 build 1000 - limited release WIN32 release 8 January 2007 - Windows Vista support. - Reduced the need for elevated administrator privileges: - Changed the location of the disk test files from the root directory of the test volume to a BurnInTest data files subdirectory (e.g from "C:\" to "C:\BurnInTest test files\") - Moved many of the files from the Program Files directory to the User directory for Windows 2000, XP and Vista. When running BurnInTest on Windows 98, ME or from a key.dat file (e.g. from a USB drive with a licensed key.dat) BurnInTest will store these files in the BurnInTest program directory. Specifically, the following files have been moved from the Program Files directory to the User Personal directory, e.g. Vista - "C:\Users\\Documents\PassMark\BurnInTest\" XP - "My Documents\PassMark\BurnInTest\" Files: Configuration file, Configuration load/save default directory, Save log file and image default directory, parallel port override "ioports.dat" directory, default command line script directory, log file directory, video file directory, Plugin directory, machine id file directory, Run as script default directory, CD burn image, Advanced network FTP temp files. - Replaced the Help system with Browser based help. - Changed the Disk test block size from 16KB to 256KB. It is planned to make this user configurable in the next build. Release 5.1 build 1014 WIN32 release 2 November 2006 WIN64 release 2 November 2006 - Corrected a bug when running on Vista, where the Standard network test would report a checksum error when the transmitted data was correct. - Corrected a bug where BurnInTest would not stop the tests based on the number of test cycles for the Plugin test or the Advanced Network test. - Made the "Could not set USB2Test mode" USB error message more specific by adding an error for insufficient system resources. - Changed the preferences Window to fit on an 800x600 resolution screen. - Corrected a minor bug in Activity level 2 trace logging with the 'hide duplicate' preference setting. - Corrected a minor memory leak if the 2D test failed to initialize (such as due to a DirectX problem). - The Parallel port test may now be used on Windows Vista. Specifically, the PassMark device driver used for the parallel port test could not be loaded on 64-bit Windows Vista as it was not digitally signed. It is now digitally signed. Release 5.1 build 1013 revision 0002 WIN32 release 19 September 2006 WIN64 release 19 September 2006 - Corrected an Access Violation problem reported by a customer on a particular MB. Release 5.1 build 1013 WIN32 release 7 September 2006 WIN64 release 7 September 2006 - The "Notes" section has been added to the Customer results certificate. - Some additional configuration range validation has been added. Release 5.1 build 1012 WIN32 release 15 August 2006 - Corrected a false report of a "Unable to get disk volume extent information" for the disk butterfly seek test. - Advanced Network test changes for errors: "Corrupt header - packet discarded" and "Advanced Network test timed out" - Advanced Network test Endpoint changes for problems on non-English Operating Systems and systems with the Windows "Network Interface" performance statistics disabled. - SMART parameters on a Samsung Hard Disk caused BurnInTest to fail when running the disk test with SMART thresholds enabled. This has been corrected. - The 2D scrolling H's test could display corrupt characters on the second and subsequent test run. This has been corrected. - A problem with the Integer maths test where the results could display a negative number of operations has been resolved. - Minor improvements to the help file. - HTML help file added for Windows Vista and Longhorn Server. - Minor improvements to the Error Classification file (error descriptions). - Some CD Trace level 1 logging has been moved to trace level 2. - Trace level 1 logging has been added to the test closing software. - New build of Endpoint.exe (1.0 1010). Release 5.1 build 1011 WIN32 release 6 July 2006 - New Advanced Network test error reporting added in the previous build V5.1 1010 has been removed. - A broader range of USB 2.0 Loopback plugs can now be used with BurnInTest. Release 5.1 build 1010 WIN32 release 4 July 2006 - Corrected the HTML report description of the L2/L3 CPU cache when the L3 cache size could not be determined. Advanced network changes: - Endpoints ran at 100% CPU load as they contained no throttling. This impacted their ability to effectively handle multiple threads handling TCP/UDP messaging. Throttling has been added to the EndPoint side to reduce CPU load. This does not greatly impact Network load. - Throttling on the BurnInTest side contained a sleep that was not insignificant. This could have impacted the BurnInTest data test thread to to handle incoming TCP and particularly UDP messages. This sleep has been reduced and other throttling parameters changed to suit. (ie. smaller sleeps more often). - EndPoint systems with x NICs (where x > 1), reported themselves as an Endpoint with x NICs, x times. Effectively registering with BurnInTest as x * x EndPoint NICS. This impacted the effectiveness of the load distribution to EndPoint NICs. An Endpoint system now only registers the once with BurnInTest. - The BurnInTest side did not report data verification Checksum errors for full duplex testing. This error determination has been corrected and reporting added. - The Test statistics sent from the Endpoint to BurnInTest could fail if the statistics block is split across 2 lower level TCP send packets. This could lead to problems like incorrect reporting of Endpoint determined checksum errors, Endpoint load and load balancing. Further it would lead to an Endpoint testthread being put into an endless TCP send loop. This would eventually bring the Endpoint system to its knees as more and more of these test threads go into this state. This has been corrected. - The Data Received reported by BurnInTest was double counted. This has been corrected. Release 5.1 build 1009 WIN32 release 23 June 2006 - Plugin test error classifications were incorrect in the log file detailed description. - Corrections to the advanced network test (BurnInTest and EndPoint). Release 5.1 build 1008 - limited release WIN32 release 20 June 2006 - Advanced network changes corrections. Most notably, a bug where part of the payload data could be lost if the payload block (eg. 1000 bytes) was split across 2 (or more) lower level TCP packets. - Added version reporting for Endpoints. Release 5.1 build 1007 - limited release WIN32 release 16 June 2006 Advanced network changes: - Corrected a BurnInTest access Violation introduced in V5.1 1006. - The Endpoint now reports its version and build to BurnInTest and BurnInTest reports this in the log file if it is an earlier version than expected. This is to help avoid the situation where old Endpoints are run on the Network, that may not be compatible with the version of BurnInTest being run by the user. - Removed a timeout report in a specific instance where a timeout is not an error. - Changed the Endpoint rebalancing and polling to occur less often after the test has been running 3 minutes. This is to help allowing the handling of polling from a larger number of multiple copies of BurnInTest on the Network. - Added a connection retries on failure for the Endpoint. - Corrected a memory leak in the Endpoint. - Increased the number of sockets supported. - Corrected some Advanced Network error classifications. Release 5.1 build 1006 - limited release WIN32 release 14 June 2006 - Improvements to the Advanced Network test (both BurnInTest V5.1 1006 and EndPoint V1.0 1004) to remove corrupted false packet corruption errors. Improved the timeout recovery mechanism. Added some validation to the Windows Network performance data used for NIC utilization. - Changes to the collection of Disk drive information on startup to try to resolve a startup issue on Systems with a large number of physical drives and 'unusual' WMI namings. Release 5.1 build 1005 WIN32 release 2 June 2006 - Corrected a bug in the Advanced network test where the test would not recover from timeout errors. The test appears to be running, but the results are 0 and the number of connected End Points are 0. Also improved the retry on timeout mechanism. - Removed some duplication in error reporting in the Advanced Network test. - Changed the Advanced Network display of Utilization to ensure a maximum of 100% displayed. - Corrected an Advanced Network test bug where the number of Errors reported in the test window would not take into account the corrupt packet threshold, and an error would be added for each occurrence of the corrupt packet (rather than when the user set threshold was reached). Release 5.1 build 1004b WIN32 release 25 May 2006 (not publicly released) - Corrected the default Advanced network corrupt packet threshold value. - Updated the data entry fields in the CD preferences when a different CD drive is selected. - The Advanced Network specific log files should be concatenated for a script run. This was only occurring for the first NIC under test. The concatenation will now occur for each NIC under test, when run from a script. - Corrected a bug where a log file name specified with no directory path could be incorrect. - Corrected a bug where the customer "Test Certificate" report incorrectly translated the "%" character from a customer specific HTML template. eg would be translated to . - The "Advanced Network test error" (215) has been removed and replaced with other existing error messages 214, 219, 220, 221 or 222. - Added the Customer name and Technician name to the text and HTMl reports. Previously, this information was only included in the "Test Certificate" report. - We have added a commandline option to specify the Serial port test data as a constant value. To specify specific data for the Serial port test you should specify e.g. "bit.exe /E 23" from the command line where 23 is in decimal and will be used for all test data (instead of random data). The vales should be between 0 and 255. Release 5.1 build 1004 WIN32 release 19 April 2006 (not publicly released) - Added the COM port speed of 921600 Kbits/s for RS 422/RS485 testing. - Changed the CD test to ensure that the entire test CD data is not cached on systems with a large amount of RAM. - Added a -M command line option to display the Machine ID window automatically when BurninTest starts. - Changed the 2D EMC scrolling H's test to work on multiple monitors were the resolution on each is different. - Changed log files such the syntax "..\" could be used for files in the directory up a level. - Minor correction to the advanced network test. Release 5.1 build 1003 WIN32 release 18 April 2006 WIN64 release 18 April 2006 - Changed the Advanced network test to allow a corrupt packet threshold value up to 1 million. - Bundled a new version of rebooter. Release 5.1 build 1002 WIN32 release 11 April 2006 WIN64 release 11 April 2006 - Corrections to the translation of V4.0 to V5 configuration files. Note: Configuration files in V5.x builds prior to V5.1 1002 could become corrupted if a V4.0 configuration file is loaded. - Corrected a bug where the main Window size and location were not restored on restarting BurnInTest. - Changes to the SMART attribute logging to support a greater range of Disk drive device drivers. Added additional Activity Level 2 trace logging. - Added an option to use CTS (Clear To Send) flow control in the loop back stage of the COM port test. - Corrected a bug where the CPU L3 cache could be reported as -1. - Help file updates. Release 5.1 build 1001 WIN32 release 30/March/2006 - Digitally signed the BurnInTest application to allow it to run under Windows Server "Longhorn". Note, previously only the installation package was digitally signed. - Updated the reported Operating system descriptions, including: - Windows Vista - Windows Server "Longhorn" - Corrected a bug where the Advanced network information was not displayed on the main window when it was run from a script. - The Advanced Network Corrupt threshold packet has been changed to produce an error every time the error is received after the threshold is reached. - Corrected the reporting of "Network, Packet discarded due to corrupt header" as a Network test error. - Corrected a bug where a new log file was not created if (only) the log prefix changed during the running of a script file. - Split the "Network, Advanced Network test error" error into 6 errors: "Network, Advanced Network test error" "Advanced Network Socket error" "Advanced Network Send error" "Advanced Network Send error - no data sent" "Advanced Network Receive error" "Advanced Network Receive error - no data received" Added either activity trace 1 or trace 2 logging for each of the errors, with additional information where available. - Added additional Serial port activity trace 2 logging. Including the logging of all transmit buffer data when the /B command line is used. Release 5.1 build 1000 WIN32 release 27/March/2006 (not a public release) Added the following features: - Create the log file directory specified in the Logging Options if it does not exist. - Condense the Advanced Network Test log files to one log file per IP address per script run, when run from a script. - Added an option to summarize duplicate errors in the log file. - Color coded errors based on severity in the Detailed event log Window and the HTML log file. - Added an option to only create a log file when BurnIn actually runs a test as opposed to every time BurnIn is executed. - Added a warning if a test thread completes with 0 cycles and 0 operations. - In the results summary html file, inserted more spacing between the 揘otes? and 揇etailed Event Log? - Changed the Activity Trace file format to be the same as the log file, ie. text or HTML, rather than always text. - The 2D 揝crolling H抯?test will now display across multiple screens/displays ?i.e. all active displays. - A threshold has been added for the 揷orrupt header ?packet discarded?event in the advanced network options so that a 揊ail?is not produced when that is the only thing that produces errors. - Added looping capability in scripting. LOOP n { ? } where n is the number of times to repeat the commands in the brackets. - Corrected a bug where PASS could be displayed if the Advanced Network test was the only test running, but it failed. Release 5.0 build 1001 WIN32 release 9/March/2006 - Corrected a bug where Network directory paths were not accepted, eg. for the log file name and post test application file name. - The CPU maths test has been improved to better load up all CPU's. Previously BurnInTest started a maths test thread per physical CPU package. BurnInTest has been changed to start a maths test thread per CPU (= num. physical CPU packages x num. CPU cores x num. logical CPUs). - The CPU preferences have been changed to allow the CPU maths test to be locked to any CPU (ie. select a CPU from a list of CPU's where the number of CPU's = num. physical CPU packages x num. CPU cores x num. logical CPUs). - The Parallel and Serial port error message have been modified in the case where a test plug may not have been connected to indicate that the user should check this. - Corrected a bug where a licenced version could display the message "[limited evaluation version]" Release 5.0 build 1000 WIN32 release 24/February/2006 WIN64 release 24/February/2006 NEW TESTS & IMPROVEMENTS TO EXISTING TESTS BurnInTest Standard and Professional versions. - Added a customer style results certificate. This will save the log file in HTML format but from the perspective of a end customer. This report style can be tailored by the user (through changing an HTML template). - An MP3 playback test has been added to the Sound test. - A color printer test has been added. - A new post test option to allow the results to be printed automatically at the end of a test has been added. - Added new Post-test action options of: - Optionally allow the user to "run an external program & exit" after BIT has been manually stopped. Modify the $RESULT variable to "PASS (manual abort)" or "FAIL (manual abort)" for this case. - Allow the results window to be displayed for all post test options (except Reboot). - Added new Pre-test actions to allow an external application to be run and have BIT wait for the application to exit. On continuing, BIT will run the subscript file (of scripting commands) if it has been created. - Changed the manual Stop buttons, to abort the running of a script (rather than just the current test). BurnInTest Professional specific. - Added a "Plugin" test that allows users to develop their own BurnInTest test modules for specialized hardware. Three external plugins may be specified at once. - A Modem test has been added to BurnInTest as a Plugin. PassMark's ModemTest Version V1.3 (latest build) is required. - A KeyBoard Test has been added to BurnInTest as a Plugin. PassMark's KeyboardTest Version V2.2 (latest build) is required. - A Firewire Test has been added to BurnInTest as a Plugin. PassMark's free Firewire plugin is required and a "Kanguru FireFlash" drive is required. - A new advanced network test has been added. BurnInTest Professional only. - The Memory test now allows the user to specify the type of test pattern to be used. - Testing with the USB 2.0 Loopback plug has been improved. When used with USB 2.0 Loopback device driver V2.0.1002, error details will now be reported for: CRC error reported by USB Host controller BIT STUFF error reported by USB Host controller DATA TOGGLE MISMATCH error reported by USB Host controller STALL PID error reported by USB Host controller DEVICE NOT RESPONDING error reported by USB Host controller PID CHECK FAILURE error reported by USB Host controller UNEXPECTED PID error reported by USB Host controller DATA OVERRUN error reported by USB Host controller DATA UNDERRUN error reported by USB Host controller BUFFER OVERRUN error reported by USB Host controller BUFFER UNDERRUN error reported by USB Host controller NOT ACCESSED error reported by USB Host controller FIFO error reported by USB Host controller TRANSACTION (XACT) ERROR reported by USB Host controller BABBLE DETECTED error reported by USB Host controller DATA BUFFER ERROR reported by USB Host controller In the case of these errors, BurnInTest will re-attempt the operation. The user can set the Error reporting to be skipped for the initial recovery attempt. IMPROVEMENTS TO TESTING FACILITIES - Added a disk autoconfig, such that when tests are started, the disk drives and settings will be defaults to all disks (exc. CD/DVD). This may be useful when testing multiple systems with different hard disk drive letters. - Store the position of the Main window on exiting BurnInTest. On starting BurnInTest, position the main window as saved; on starting tests, position the test windows as saved. - Allow a "drag & drop" of the Configuration file directly on the BurnInTest program icon. - Allow testing 99.5% to 100% of disk, instead of 94%, for disks that do not contain the Windows directory and do not contain a swap file. - Added the ability to log interim results, which may be useful for unstable systems. - AMD and Intel Dual core reporting added. - New L2 CPU cache sizes added to reports. - CPU support for SSE3, DEP and PAE added to reports. - Shortcut of "F1" for contextual help added to all Windows. - Improve the flexibility in specifying the EXECUTEWAIT scripting command for sleeper. - Updated logging header information with the hard and optical drive model. - The 2D and 3D tests have been updated to use DirectX 9.0c. - User interface updated. - The HTML report format has been improved. - The BurnInTest configuration file extension has been renamed from .cfg to use .bitcfg, to ensure the configuration file is associated with BurnInTest. - An error message indicating that accumulated log files are not supported when run from CD or DVD has been added. - To allow smaller test files with very large disks, the minimum disk test file size has been reduced from 0.1% to 0.01% of the disk space. - Log events were previously shown as "INFORMATION" if they were low level errors, or simply additional information (not errors). "INFORMATION" now refers to a low level error, and "LOG NOTE" now refers to additional information (that is not in the error count). - Improved the specific detail of the Serial Port errors detected. BurnInTest now reports framing errors, buffer overrun errors, input buffer overflow errors, parity errors and Transmit buffer full errors as specific error messages (rather than a broader error description). - Added the /k command line so the user can specify not to delete HDD test files if an error occurs. - Increased Activity trace level 1 error logging for Serial port testing. - Increased Activity trace level 1 error logging for Hyper threading detection. - Bundled a new version of the Rebooter program. - Improved the Serial port error logging (displaying baud rate) and increased Activity trace level 1 error logging (displaying erroneous data). - Modified the Window sizes to help improve navigation on smaller displays (i.e. 640x480). - The CPU load for the Standard and Torture RAM tests has been made more linear with the duty cycle setting. Note: This means that compared to the previous build of BurnInTest, less RAM test operations will be run per second (when the duty cycle is less than 100). - Additional debug code and very minor changes in the Loopback sound test. - The Post test option of "Run external application and exit" has been modified such that if no external file is specified, this Post test option will just exit BurnInTest. - Allowed the full range of PassMark USB1 loopback plugs to be used with BurnInTest Professional. - Added additional Activity Trace level 2 logging. - The delay inserted between packets in the USB2 test, when the duty cycle is less than 50, has been changed from at least 1ms to at least 1ms to 50ms (for a Duty Cycle of 49 down to 0). - The subscript commands to configure BurnInTest from an external application (i.e. specified in the bit-script-input.txt file and run by specifying either a pre-test or EXECUTEWAIT application) has been changed to allow "LOAD" commands (in addition to "SET" scripting commands). - Renamed the "Error" log to "Event" log. - Changed the order of the items in an Event log line, such that the Severity is the first item. - The EXECUTEWAIT script command has been modified such that the external application may provide an input script file (of SET... commands) to be run after the EXECUTEWAIT application closes. This allows external applications to define test environment parameters (such as the serial number and machine type). - Added scripting commands: SETSERIAL "1234-shdfgdhs-GHGHG" SETMACHINETYPE "HP XPS800" SETNOTES "Test notes defined by the external application." SETLOG "\Program Files\Plugin\plugin_log" SETPLUGIN "\Program Files\Plugin\plugin.exe" - Added POST TEST application parameter substitution to allow values to be passed to an external application at the end of a test. These are: $RESULT - "PASS" or "FAIL" will be substituted. $SERIAL - The serial number will be substituted. $MACHINETYPE - The machine type will be substituted. $NOTES - The notes will be substituted. - Added extra logging for memory allocation errors in the disk test - Added "log bad sector increase" and "bad sector threshold" options to disk test. This resulted in a change to the configuration file format and required additional code to automatically convert from old formats. - Modified the user interface in the preferences window for the disk test and the CD test - Improved the handling of USB 2.0 loopback plugs recovery from sleep states. BUG CORRECTIONS - Corrected a bug where the System and Application events logged in the BurnInTest Trace logs were wrong if the event log had reached its maximum size. - Checks that the Sound test files (WAV and MIDI) exist have been added. - The continuous auto updating of the USB image (USB Loopback plug vs. USB 2.0 Loopback plug) on the main window has been removed. This is now updated on BIT startup, selecting Refresh in USB preferences or on starting a test. If there is a serious USB problem, this (together with the USB 2.0 Loopback device driver, V2.0.1002) will avoid the possibility of BurnInTest locking up. - Corrected a bug with the Butterfly seek mode of the Disk test. This was found to occur with FAT32 disks where the Cylinder size was relatively small and the Sector size relatively large. - Reset Defaults on the Configuration Page now resets the Auto Stop Value. - Reset Defaults on the Configuration Page now resets the color indicators. - The CD test has been modified to skip invalid files either with "?"'s , to avoid reporting errors that are due to the CD test media filenames. - The Network test results window scroll bar has been corrected. - The Memory torture test could fail on some systems with a small amount of RAM and relatively high memory fragmentation. This has been corrected. - Scripting correction for .cmd files. - Corrected a bug that caused problems when running the disk test with SMART monitoring turned on. This problem only occurs on a small number of HDD's. - Corrected memory leaks - On occasion, the measured waveform from the loopback sound test may have been slightly altered on starting or stopping all tests, possibly enough to trigger an error. This has been resolved. - If an error occurred in the final second of a test, the error may have been logged but not included in the big PASS/FAIL results window. This has been corrected. - After running a script file that loaded a configuration file, that had a full path specified, the Save and Load configuration menu options no longer worked. This has been corrected. - Previously, the Version of BurnInTest was only written in the First log file after starting BurnInTest. This log line is now written in all log files. - For USB2 tests that have read or write failures, the Windows error codes are now included in the level 2 Activity trace log. - Command line parameters may now be passed to a PreTest application. - Log files may now use a single static filename. This may be useful when the log file is to be parsed by an external program. - Corrected a bug where the Plugin test would stop prematurely. - Corrected the specification of the Scripting EXECUTEWAIT filename. - Changed Script processing such that a script is aborted if a scripting error is encountered and Stop on error is selected. - Added an indication on the main window that a script is currently running ("Script currently running"). - Corrected the serial port test to identify non-existing plugs when the Disable RTS/CTS and DSR/DTR testing has been selected. - Corrected the display of strange results (666666) reported by a user, related to copy protection. - Fixed a memory leak bug in the MBM interface which caused memory allocation errors. - Added BIT version number to the ASCII log file. - Fixed a bug with the 3D Test that was causing it to stop before the autostop timer period - Changed an error in the tape drive test to a warning if tape drive doesn't support setting drive parameters. History of earlier releases: Please see http://passmark.com/products/bit_history.htm Documentation ============= All the documentation is included in the help file. It can be accessed from the help menu. There is also a PDF format Users guide available for download from the PassMark web site. Support ======= For technical support, questions, suggestions, please check the help file for our email address or visit our web page at http://www.passmark.com Ordering / Registration ======================= All the details are in the help file documentation or you can visit our sales information page http://www.passmark.com/sales Compatibility issues with the Network & Parallel Port Tests =========================================================== If you are running Windows 2000 or XP, you need to have administrator privileges to run this test. Enjoy.. The PassMark Development team
https://github.com/iBotPeaches/Apktool Introduction Basic First lets take a lesson into apk files. apks are nothing more than a zip file containing resources and compiled java. If you were to simply unzip an apk like so, you would be left with files such as classes.dex and resources.arsc. $ unzip testapp.apk Archive: testapp.apk inflating: AndroidManifest.xml inflating: classes.dex extracting: res/drawable-hdpi/ic_launcher.png inflating: res/xml/literals.xml inflating: res/xml/references.xml extracting: resources.arsc However, at this point you have simply inflated compiled sources. If you tried to view AndroidManifest.xml. You'd be left viewing this. P4F0\fnversionCodeversionNameandroid*http://schemas.android.com/apk/res/androidpackageplatformBuildVersionCodeplatformBuildVersionNamemanifestbrut.apktool.testapp1.021APKTOOL Obviously, editing or viewing a compiled file is next to impossible. That is where Apktool comes into play. $ apktool d testapp.apk I: Using Apktool 2.0.0 on testapp.apk I: Loading resource table... I: Decoding AndroidManifest.xml with resources... I: Loading resource table from file: 1.apk I: Regular manifest package... I: Decoding file-resources... I: Decoding values */* XMLs... I: Baksmaling classes.dex... I: Copying assets and libs... $ Viewing AndroidManifest.xml again results in something much more human readable <?xml version="1.0" encoding="utf-8" standalone="no"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="brut.apktool.testapp" platformBuildVersionCode="21" platformBuildVersionName="APKTOOL"/> In addition to XMLs, resources such as 9 patch images, layouts, strings and much more are correctly decoded to source form. Decoding The decode option on Apktool can be invoked either from d or decode like shown below. $ apktool d foo.jar // decodes foo.jar to foo.jar.out folder $ apktool decode foo.jar // decodes foo.jar to foo.jar.out folder $ apktool d bar.apk // decodes bar.apk to bar folder $ apktool decode bar.apk // decodes bar.apk to bar folder $ apktool d bar.apk -o baz // decodes bar.apk to baz folder Building The build option can be invoked either from b or build like shown below $ apktool b foo.jar.out // builds foo.jar.out folder into foo.jar.out/dist/foo.jar file $ apktool build foo.jar.out // builds foo.jar.out folder into foo.jar.out/dist/foo.jar file $ apktool b bar // builds bar folder into bar/dist/bar.apk file $ apktool b . // builds current directory into ./dist $ apktool b bar -o new_bar.apk // builds bar folder into new_bar.apk $ apktool b bar.apk // WRONG: brut.androlib.AndrolibException: brut.directory.PathNotExist: apktool.yml // Must use folder, not apk/jar file InfoIn order to run a rebuilt application. You must resign the application. Android documentation can help with this. Frameworks Frameworks can be installed either from if or install-framework, in addition two parameters -p, --frame-path <dir> - Store framework files into <dir> -t, --tag <tag> - Tag frameworks using <tag> Allow for a finer control over how the files are named and how they are stored. $ apktool if framework-res.apk I: Framework installed to: 1.apk // pkgId of framework-res.apk determines number (which is 0x01) $ apktool if com.htc.resources.apk I: Framework installed to: 2.apk // pkgId of com.htc.resources is 0x02 $ apktool if com.htc.resources.apk -t htc I: Framework installed to: 2-htc.apk // pkgId-tag.apk $ apktool if framework-res.apk -p foo/bar I: Framework installed to: foo/bar/1.apk $ apktool if framework-res.apk -t baz -p foo/bar I: Framework installed to: foo/bar/1-baz.apk Migration Instructions v2.1.1 -> v2.2.0 Run the following commands to migrate your framework directory Apktool will work fine without running these commands, this will just cleanup abandoned files unix - mkdir -p ~/.local/share; mv ~/apktool ~/.local/share windows - move %USERPROFILE%\apktool %USERPROFILE%\AppData\Local v2.0.1 -> v2.0.2 Update apktool to v2.0.2 Remove framework file $HOME/apktool/framework/1.apk due to internal API update (Android Marshmallow) v1.5.x -> v2.0.0 Java 1.7 is required Update apktool to v2.0.0 aapt is now included inside the apktool binary. It's not required to maintain your own aapt install under $PATH. (However, features like -a / --aapt are still used and can override the internal aapt) The addition of aapt replaces the need for separate aapt download packages. Helper Scripts may be found here Remove framework $HOME/apktool/framework/1.apk Eagle eyed users will notice resources are now decoded before sources now. This is because we need to know the API version via the manifest for decoding the sources Parameter Changes Smali/baksmali 2.0 are included. This is a big change from 1.4.2. Please read the smali updates here for more information -o / --output is now used for the output of apk/directory -t / --tag is required for tagging framework files -advance / --advanced will launch advance parameters and information on the usage output -m / --match-original is a new feature for apk analysis. This retains the apk is nearly original format, but will make rebuild more than likely not work due to ignoring the changes that newer aapt requires After [d]ecode, there will be new folders (original / unknown) in the decoded apk folder original = META-INF folder / AndroidManifest.xml, which are needed to retain the signature of apks to prevent needing to resign. Used with -c / --copy-original on [b]uild unknown = Files / folders that are not part of the standard AOSP build procedure. These files will be injected back into the rebuilt APK. apktool.yml collects more information than last version SdkInfo - Used to repopulate the sdk information in AndroidManifest.xml since newer aapt requires version information to be passed via parameter packageInfo - Used to help support Android 4.2 renamed manifest feature. Automatically detects differences between resource and manifest and performs automatic --rename-manifest-package on [b]uild versionInfo - Used to repopulate the version information in AndroidManifest.xml since newer aapt requires version information to be passed via parameter compressionType - Used to determine the compression that resources.arsc had on the original apk in order to replicate during [b]uild unknownFiles - Used to record name/location of non-standard files in an apk in order to place correctly on rebuilt apk sharedLibrary - Used to help support Android 5 shared library feature by automatically detecting shared libraries and using --shared-lib on [b]uild Examples of new usage in 2.0 vs 1.5.x Old (Apktool 1.5.x) New (Apktool 2.0.x) apktool if framework-res.apk tag apktool if framework-res.apk -t tag apktool d framework-res.apk output apktool d framework.res.apk -o output apktool b output new.apk apktool b output -o new.apk v1.4.x -> v1.5.1 Update apktool to v1.5.1 Update aapt manually or use package r05-ibot via downloading Mac, Windows or Linux Remove framework file $HOME/apktool/framework/1.apk Intermediate Framework Files As you probably know, Android apps utilize code and resources that are found on the Android OS itself. These are known as framework resources and Apktool relies on these to properly decode and build apks. Every Apktool release contains internally the most up to date AOSP framework at the time of the release. This allows you to decode and build most apks without a problem. However, manufacturers add their own framework files in addition to the regular AOSP ones. To use apktool against these manufacturer apks you must first install the manufacturer framework files. Example Lets say you want to decode HtcContacts.apk from an HTC device. If you try you will get an error message. $ apktool d HtcContacts.apk I: Loading resource table... I: Decoding resources... I: Loading resource table from file: 1.apk W: Could not decode attr value, using undecoded value instead: ns=android, name=drawable W: Could not decode attr value, using undecoded value instead: ns=android, name=icon Can't find framework resources for package of id: 2. You must install proper framework files, see project website for more info. We must get HTC framework resources before decoding this apk. We pull com.htc.resources.apk from our device and install it $ apktool if com.htc.resources.apk I: Framework installed to: 2.apk Now we will try this decode again. $ apktool d HtcContacts.apk I: Loading resource table... I: Decoding resources... I: Loading resource table from file: /home/brutall/apktool/framework/1.apk I: Loading resource table from file: /home/brutall/apktool/framework/2.apk I: Copying assets and libs... As you can see. Apktool leveraged both 1.apk and 2.apk framework files in order to properly decode this application. Finding Frameworks For the most part any apk in /system/framework on a device will be a framework file. On some devices they might reside in /data/system-framework and even cleverly hidden in /system/app or /system/priv-app. They are usually named with the naming of "resources", "res" or "framework". Example HTC has a framework called com.htc.resources.apk, LG has one called lge-res.apk After you find a framework file you could pull it via adb pull /path/to/file or use a file manager application. After you have the file locally, pay attention to how Apktool installs it. The number that the framework is named during install corresponds to the pkgId of the application. These values should range from 1 to 9. Any APK that installs itself as 127 is 0x7F which is an internal pkgId. Internal Frameworks Apktool comes with an internal framework like mentioned above. This file is copied to $HOME/apktool/framework/1.apk during use. Warning Apktool has no knowledge of what version of framework resides there. It will assume its up to date, so delete the file during Apktool upgrades Managing framework files Frameworks are stored in $HOME/apktool/framework for Windows and Unix systems. Mac OS X has a slightly different folder location of $HOME/Library/apktool/framework. If these directories are not available it will default to java.io.tmpdir which is usually /tmp. This is a volatile directory so it would make sense to take advantage of the parameter --frame-path to select an alternative folder for framework files. Note Apktool has no control over the frameworks once installed, but you are free to manage these files on your own. Tagging framework files Frameworks are stored in the naming convention of: <id>-<tag>.apk. They are identified by pkgId and optionally custom tag. Usually tagging frameworks isn't necessary, but if you work on apps from many different devices and they have incompatible frameworks, you will need some way to easily switch between them. You could tag frameworks by: $ apktool if com.htc.resources.apk -t hero I: Framework installed to: /home/brutall/apktool/framework/2-hero.apk $ apktool if com.htc.resources.apk -t desire I: Framework installed to: /home/brutall/apktool/framework/2-desire.apk Then: $ apktool d HtcContacts.apk -t hero I: Loading resource table... I: Decoding resources... I: Loading resource table from file: /home/brutall/apktool/framework/1.apk I: Loading resource table from file: /home/brutall/apktool/framework/2-hero.apk I: Copying assets and libs... $ apktool d HtcContacts.apk -t desire I: Loading resource table... I: Decoding resources... I: Loading resource table from file: /home/brutall/apktool/framework/1.apk I: Loading resource table from file: /home/brutall/apktool/framework/2-desire.apk I: Copying assets and libs... You don't have to select a tag when building apk - apktool automatically uses the same tag, as when decoding. Smali Debugging Warning SmaliDebugging has been marked as deprecated in 2.0.3, and removed in 2.1. Please check SmaliIdea for a debugger. Apktool makes possible to debug smali code step by step, watch variables, set breakpoints, etc. General information Generally we need several things to run Java debugging session: debugger server (usually Java VM) debugger client (usually IDE like IntelliJ, Eclipse or Netbeans) client must have sources of debugged application server must have binaries compiled with debugging symbols referencing these sources sources must be java files with at least package and class definitions, to properly connect them with debugging symbols In our particular situation we have: server: Monitor (Previously DDMS), part of Android SDK, standard for debugging Android applications - explained here client: any JPDA client - most of decent IDEs have support for this protocol. sources: smali code modified by apktool to satisfy above requirements (".java" extension, class declaration, etc.). Apktool modifies them when decoding apk in debug mode. binaries: when building apk in debug mode, apktool removes original symbols and adds new, which are referencing smali code (line numbers, registers/variables, etc.) Info To successfully run debug sessions, the apk must be both decoded and built in debug mode. Decoding with debug decodes the application differently to allow the debug rebuild option to inject lines allowing the debugger to identify variables and types.-d / --debug General instructions Above information is enough to debug smali code using apktool, but if you aren't familiar with DDMS and Java debugging, then you probably still don't know how to do it. Below are simple instructions for doing it using IntelliJ or Netbeans. Decode apk in debug mode: $ apktool d -d -o out app.apk Build new apk in debug mode: $ apktool b -d out Sign, install and run new apk. Follow sub-instructions below depending on IDE. IntelliJ (Android Studio) instructions In IntelliJ add new Java Module Project selecting the "out" directory as project location and the "smali" subdirectory as content root dir. Run Monitor (Android SDK /tools folder), find your application on a list and click it. Note port information in last column - it should be something like "86xx / 8700". In IntelliJ: Debug -> Edit Configurations. Since this is a new project, you will have to create a Debugger. Create a Remote Debugger, with the settings on "Attach" and setting the Port to 8700 (Or whatever Monitor said). The rest of fields should be ok, click "Ok". Start the debugging session. You will see some info in a log and debugging buttons will show up in top panel. Set breakpoint. You must select line with some instruction, you can't set breakpoint on lines starting with ".", ":" or "#". Trigger some action in application. If you run at breakpoint, then thread should stop and you will be able to debug step by step, watch variables, etc. Netbeans instructions In Netbeans add new Java Project with Existing Sources, select "out" directory as project root and "smali" subdirectory as sources dir. Run DDMS, find your application on a list and click it. Note port information in last column - it should be something like "86xx / 8700". In Netbeans: Debug -> Attach Debugger -> select JPDA and set Port to 8700 (or whatever you saw in previous step). Rest of fields should be ok, click "Ok". Debugging session should start: you will see some info in a log and debugging buttons will show up in top panel. Set breakpoint. You must select line with some instruction, you can't set breakpoint on lines starting with ".", ":" or "#". Trigger some action in application. If you run at breakpoint, then thread should stop and you will be able to debug step by step, watch variables, etc. Limitations/Issues Because IDE doesn't have full sources, it doesn't know about class members and such. Variables watching works because most of data could be read from memory (objects in Java know about their types), but if for example, you watch an object and it has some nulled member, then you won't see, what type this member is. 9Patch Images Docs exist for the mysterious 9patch images here and there. (Read these first). These docs though are meant for developers and lack information for those who work with already compiled 3rd party applications. There you can find information how to create them, but no information about how they actually work. I will try and explain it here. The official docs miss one point that 9patch images come in two forms: source & compiled. source - You know this one. You find it in the source of an application or freely available online. These are images with a black border around them. compiled - The mysterious form found in apk files. There are no borders and the 9patch data is written into a binary chunk called npTc. You can't see or modify it easily, but Android OS can as its quicker to read. There are problems related to the above two points. You can't move 9patch images between both types without a conversion. If you try and unpack 9patch images from an apk and use it in the source of another, you will get errors during build. Also vice versa, you cannot take source 9patch images directly into an apk. 9patch binary chunk isn't recognized by modern image processing tools. So modifying the compiled image will more than likely break the npTc chunk, thus breaking the image on the device. The only solution to this problem is to easily convert between these two types. The encoder (which takes source to compiled) is built into the aapt tool and is automatically used during build. This means we only need to build a decoder which has been in apktool since v1.3.0 and is automatically ran on all 9patch images during decode. So if you want to modify 9patch images, don't do it directly. Use apktool to decode the application (including the 9patch images) and then modify the images. At that point when you build the application back, the source 9patch images will be compiled. Other FAQ What about the -j switch shown from the original YouTube videos? Read Issue 199. In short - it doesn't exist. Is it possible to run apktool on a device? Sadly not. There are some incompatibilities with SnakeYAML, java.nio and aapt Where can I download sources of apktool? From our Github or Bitbucket project. Resulting apk file is much smaller than original! Is there something missing? There are a couple of reasons that might cause this. Apktool builds unsigned apks. This means an entire directory META-INF is missing. New aapt binary. Newer versions of apktool contain a newer aapt which optimizes images differently. These points might have contributed to a smaller than normal apk There is no META-INF dir in resulting apk. Is this ok? Yes. META-INF contains apk signatures. After modifying the apk it is no longer signed. You can use -c / --copy-original to retain these signatures. However, using -c uses the original AndroidManifest.xml file, so changes to it will be lost. What do you call "magic apks"? For some reason there are apks that are built using modified build tools. These apks don't work on a regular AOSP Android build, but usually are accompanied by a modified system that can read these modified apks. Apktool cannot handle these apks, therefore they are "magic". Could I integrate apktool into my own tool? Could I modify apktool sources? Do I have to credit you? Actually the Apache License, which apktool uses, answers all these questions. Yes you can redistribute and/or modify apktool without my permission. However, if you do it would be nice to add our contributors (brut.all, iBotPeaches and JesusFreke) into your credits but it's not required. Where does apktool store its framework files? unix - $HOME/.local/share/apktool mac - $HOME/Library/apktool windows - $HOME/AppData/Local/apktool Options Utility Options that can be executed at any time. -version, --version Outputs current version. (Ex: 1.5.2) -v, --verbose Verbose output. Must be first parameter -q, --quiet Quiet output. Must be first parameter -advance, --advanced Advance usage output Decode These are all the options when decoding an apk. --api <API> The numeric api-level of the smali files to generate (defaults to targetSdkVersion) -b, --no-debug-info Prevents baksmali from writing out debug info (.local, .param, .line, etc). Preferred to use if you are comparing smali from the same APK of different versions. The line numbers and debug will change among versions, which can make DIFF reports a pain. -f, --force Force delete destination directory. Use when trying to decode to a folder that already exists --keep-broken-res - Advanced If there is an error like "Invalid Config Flags Detected. Dropping Resources...". This means that APK has a different structure then Apktool can handle. This might be a newer Android version or a random APK that doesn't match standards. Running this will allow the decode, but then you have to manually fix the folders with -ERR in them. -m, --match-original - Used for analysis Matches files closest as possible to original, but prevents rebuild. -o, --output <DIR> The name of the folder that apk gets written to -p, --frame-path <DIR> The folder location where framework files should be stored/read from -r, --no-res This will prevent the decompile of resources. This keeps the resources.arsc intact without any decode. If only editing Java (smali) then this is the recommend for faster decompile & rebuild -s, --no-src This will prevent the disassemble of the dex files. This keeps the apk classes.dex file and simply moves it during build. If your only editing the resources. This is recommended for faster decompile & rebuild -t, --frame-tag <TAG> Uses framework files tagged via <TAG> Rebuild These are all the options when building an apk. -a, --aapt <FILE> Loads aapt from the specified file location, instead of relying on path. Falls back to $PATH loading, if no file found -c, --copy-original - Will still require signature resign post API18 Copies original AndroidManifest.xml and META-INF folder into built apk -d, --debug Adds debuggable="true" to AndroidManifest file. -f, --force-all Overwrites existing files during build, reassembling the resources.arsc file and classes.dex file -o, --output <FILE> The name and location of the apk that gets written -p, --frame-path <DIR> The location where framework files are loaded from
Table of Contents Header Files The #define Guard Header File Dependencies Inline Functions The -inl.h Files Function Parameter Ordering Names and Order of Includes Scoping Namespaces Nested Classes Nonmember, Static Member, and Global Functions Local Variables Static and Global Variables Classes Doing Work in Constructors Default Constructors Explicit Constructors Copy Constructors Structs vs. Classes Inheritance Multiple Inheritance Interfaces Operator Overloading Access Control Declaration Order Write Short Functions Google-Specific Magic Smart Pointers cpplint Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and Predecrement Use of const Integer Types 64-bit Portability Preprocessor Macros 0 and NULL sizeof Boost C++0x Naming General Naming Rules File Names Type Names Variable Names Constant Names Function Names Namespace Names Enumerator Names Macro Names Exceptions to Naming Rules Comments Comment Style File Comments Class Comments Function Comments Variable Comments Implementation Comments Punctuation, Spelling and Grammar TODO Comments Deprecation Comments Formatting Line Length Non-ASCII Characters Spaces vs. Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Pointer and Reference Expressions Boolean Expressions Return Values Variable and Array Initialization Preprocessor Directives Class Format Constructor Initializer Lists Namespace Formatting Horizontal Whitespace Vertical Whitespace Exceptions to the Rules Existing Non-conformant Code Windows Code Important Note Displaying Hidden Details in this Guide link ▶This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below. Hooray! Now you know you can expand points to get more details. Alternatively, there's an "expand all" at the top of this document. Background C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain. The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively. Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting. One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency. Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted. Open-source projects developed by Google conform to the requirements in this guide. Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language. Header Files In general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function. Correct use of header files can make a huge difference to the readability, size and performance of your code. The following rules will guide you through the various pitfalls of using header files. The #define Guard link ▶All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be ___H_. To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in project foo should have the following guard: #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... #endif // FOO_BAR_BAZ_H_ Header File Dependencies link ▶Don't use an #include when a forward declaration would suffice. When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files. You can significantly minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #include "file/base/file.h". How can we use a class Foo in a header file without access to its definition? We can declare data members of type Foo* or Foo&. We can declare (but not define) functions with arguments, and/or return values, of type Foo. (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.) We can declare static data members of type Foo. This is because static data members are defined outside the class definition. On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of type Foo. Sometimes it makes sense to have pointer (or better, scoped_ptr) members instead of object members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files. Of course, .cc files typically do require the definitions of the classes they use, and usually have to include several header files. Note: If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in myfile.cc, it's ok to #include (or forward-declare) Foo in myfile.h, instead of myfile.cc. Inline Functions link ▶Define functions inline only when they are small, say, 10 lines or less. Definition: You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism. Pros: Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions. Cons: Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. Decision: A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls! Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed). It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators. The -inl.h Files link ▶You may use file names with a -inl.h suffix to define complex inline functions when needed. The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in .cc files, and we do not like to have much actual code in .h files unless there is a readability or performance advantage. If an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a .h file for the convenience of the implementer and callers, though if this makes the .h file too unwieldy you can instead put that code in a separate -inl.h file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary. Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read. Do not forget that a -inl.h file requires a #define guard just like any other header file. Function Parameter Ordering link ▶When defining a function, parameter order is: inputs, then outputs. Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be non-const pointers. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output (often classes/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Names and Order of Includes link ▶Use standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries' .h, your project's .h. All of a project's header files should be listed as descentants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For example, google-awesome-project/src/base/logging.h should be included as #include "base/logging.h" In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows: dir2/foo2.h (preferred location — see details below). C system files. C++ system files. Other libraries' .h files. Your project's .h files. The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first .h file #included in some .cc. dir/foo.cc and dir2/foo2.h are often in the same directory (e.g. base/basictypes_test.cc and base/basictypes.h), but can be in different directories too. Within each section it is nice to order the includes alphabetically. For example, the includes in google-awesome-project/src/foo/internal/fooserver.cc might look like this: #include "foo/public/fooserver.h" // Preferred location. #include #include #include #include #include "base/basictypes.h" #include "base/commandlineflags.h" #include "foo/public/bar.h" Scoping Namespaces link ▶Unnamed namespaces in .cc files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive. Definition: Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope. Pros: Namespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. For example, if two different projects have a class Foo in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, project1::Foo and project2::Foo are now distinct symbols that do not collide. Cons: Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR). Decision: Use namespaces according to the policy described below. Unnamed Namespaces Unnamed namespaces are allowed and even encouraged in .cc files, to avoid runtime naming conflicts: namespace { // This is in a .cc file. // The content of a namespace is not indented enum { kUnused, kEOF, kError }; // Commonly used tokens. bool AtEof() { return pos_ == kEOF; } // Uses our namespace's EOF. } // namespace However, file-scope declarations that are associated with a particular class may be declared in that class as types, static data members or static member functions rather than as members of an unnamed namespace. Terminate the unnamed namespace as shown, with a comment // namespace. Do not use unnamed namespaces in .h files. Named Namespaces Named namespaces should be used as follows: Namespaces wrap the entire source file after includes, gflags definitions/declarations, and forward declarations of classes from other namespaces: // In the .h file namespace mynamespace { // All declarations are within the namespace scope. // Notice the lack of indentation. class MyClass { public: ... void Foo(); }; } // namespace mynamespace // In the .cc file namespace mynamespace { // Definition of functions is within scope of the namespace. void MyClass::Foo() { ... } } // namespace mynamespace The typical .cc file might have more complex detail, including the need to reference classes in other namespaces. #include "a.h" DEFINE_bool(someflag, false, "dummy flag"); class C; // Forward declaration of class C in the global namespace. namespace a { class A; } // Forward declaration of a::A. namespace b { ...code for b... // Code goes against the left margin. } // namespace b Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file. You may not use a using-directive to make all names from a namespace available. // Forbidden -- This pollutes the namespace. using namespace foo; You may use a using-declaration anywhere in a .cc file, and in functions, methods or classes in .h files. // OK in .cc files. // Must be in a function, method or class in .h files. using ::foo::bar; Namespace aliases are allowed anywhere in a .cc file, anywhere inside the named namespace that wraps an entire .h file, and in functions and methods. // Shorten access to some commonly used names in .cc files. namespace fbz = ::foo::bar::baz; // Shorten access to some commonly used names (in a .h file). namespace librarian { // The following alias is available to all files including // this header (in namespace librarian): // alias names should therefore be chosen consistently // within a project. namespace pd_s = ::pipeline_diagnostics::sidetable; inline void my_inline_function() { // namespace alias local to a function (or method). namespace fbz = ::foo::bar::baz; ... } } // namespace librarian Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible. Nested Classes link ▶Although you may use public nested classes when they are part of an interface, consider a namespace to keep declarations out of the global scope. Definition: A class can define another class within it; this is also called a member class. class Foo { private: // Bar is a member class, nested within Foo. class Bar { ... }; }; Pros: This is useful when the nested (or member) class is only used by the enclosing class; making it a member puts it in the enclosing class scope rather than polluting the outer scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the .cc file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation. Cons: Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a Foo::Bar* pointer will have to include the full class declaration for Foo. Decision: Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method. Nonmember, Static Member, and Global Functions link ▶Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely. Pros: Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace. Cons: Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies. Decision: Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead. Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library. If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {...}) to limit its scope. Local Variables link ▶Place a function's variables in the narrowest scope possible, and initialize variables in the declaration. C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g. int i; i = f(); // Bad -- initialization separate from declaration. int j = g(); // Good -- declaration has initialization. Note that gcc implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scopes declarations in if and while statements, e.g. while (const char* p = strchr(str, '/')) str = p + 1; There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope. // Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 times each. f.DoSomething(i); } It may be more efficient to declare such a variable used in a loop outside that loop: Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); } Static and Global Variables link ▶Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction. Objects with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays/structs of POD. The order in which class constructors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals. Likewise, the order in which destructors are called is defined to be the reverse of the order in which the constructors were called. Since constructor order is indeterminate, so is destructor order. For example, at program-end time a static variable might have been destroyed, but code still running -- perhaps in another thread -- tries to access it and fails. Or the destructor for a static 'string' variable might be run prior to the destructor for another variable that contains a reference to that string. As a result we only allow static variables to contain POD data. This rule completely disallows vector (use C arrays instead), or string (use const char []). If you need a static or global variable of a class type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a "smart" pointer, since the smart pointer's destructor will have the order-of-destructor issue that we are trying to avoid. Classes Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class. Doing Work in Constructors link ▶In general, constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. Definition: It is possible to perform initialization in the body of the constructor. Pros: Convenience in typing. No need to worry about whether the class has been initialized or not. Cons: The problems with doing work in constructors are: There is no easy way for constructors to signal errors, short of using exceptions (which are forbidden). If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state. If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion. If someone creates a global variable of this type (which is against the rules, but still), the constructor code will be called before main(), possibly breaking some implicit assumptions in the constructor code. For instance, gflags will not yet have been initialized. Decision: If your object requires non-trivial initialization, consider having an explicit Init() method. In particular, constructors should not call virtual functions, attempt to raise errors, access potentially uninitialized global variables, etc. Default Constructors link ▶You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly. Definition: The default constructor is called when we new a class object with no arguments. It is always called when calling new[] (for arrays). Pros: Initializing structures by default, to hold "impossible" values, makes debugging much easier. Cons: Extra work for you, the code writer. Decision: If your class defines member variables and has no other constructors you must define a default constructor (one that takes no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid. The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly. If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor. Explicit Constructors link ▶Use the C++ keyword explicit for constructors with one argument. Definition: Normally, if a constructor takes one argument, it can be used as a conversion. For instance, if you define Foo::Foo(string name) and then pass a string to a function that expects a Foo, the constructor will be called to convert the string into a Foo and will pass the Foo to your function for you. This can be convenient but is also a source of trouble when things get converted and new objects created without you meaning them to. Declaring a constructor explicit prevents it from being invoked implicitly as a conversion. Pros: Avoids undesirable conversions. Cons: None. Decision: We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name); The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments. Copy Constructors link ▶Provide a copy constructor and assignment operator only when necessary. Otherwise, disable them with DISALLOW_COPY_AND_ASSIGN. Definition: The copy constructor and assignment operator are used to create copies of objects. The copy constructor is implicitly invoked by the compiler in some situations, e.g. passing objects by value. Pros: Copy constructors make it easy to copy objects. STL containers require that all contents be copyable and assignable. Copy constructors can be more efficient than CopyFrom()-style workarounds because they combine construction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation. Cons: Implicit copying of objects in C++ is a rich source of bugs and of performance problems. It also reduces readability, as it becomes hard to track which objects are being passed around by value as opposed to by reference, and therefore where changes to an object are reflected. Decision: Few classes need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer instead of by value, and you can store pointers rather than objects in an STL container. If your class needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy constructor and assignment operator. If your class does not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the private: section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error). For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used: // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) Then, in class Foo: class Foo { public: Foo(int f); ~Foo(); private: DISALLOW_COPY_AND_ASSIGN(Foo); }; Structs vs. Classes link ▶Use a struct only for passive objects that carry data; everything else is a class. The struct and class keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining. structs should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, destructor, Initialize(), Reset(), Validate(). If more functionality is required, a class is more appropriate. If in doubt, make it a class. For consistency with STL, you can use struct instead of class for functors and traits. Note that member variables in structs and classes have different naming rules. Inheritance link ▶Composition is often more appropriate than inheritance. When using inheritance, make it public. Definition: When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and interface inheritance, in which only method names are inherited. Pros: Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API. Cons: For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class. Decision: All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead. Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar "is a kind of" Foo. Make your destructor virtual if necessary. If your class has virtual methods, its destructor should be virtual. Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private. When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not. Multiple Inheritance link ▶Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be pure interface classes tagged with the Interface suffix. Definition: Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are pure interfaces and those that have an implementation. Pros: Multiple implementation inheritance may let you re-use even more code than single inheritance (see Inheritance). Cons: Only very rarely is multiple implementation inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution. Decision: Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure interfaces. In order to ensure that they remain pure interfaces, they must end with the Interface suffix. Note: There is an exception to this rule on Windows. Interfaces link ▶Classes that satisfy certain conditions are allowed, but not required, to end with an Interface suffix. Definition: A class is a pure interface if it meets the following requirements: It has only public pure virtual ("= 0") methods and static methods (but see below for destructor). It may not have non-static data members. It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected. If it is a subclass, it may only be derived from classes that satisfy these conditions and are tagged with the Interface suffix. An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, they must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details. Pros: Tagging a class with the Interface suffix lets others know that they must not add implemented methods or non static data members. This is particularly important in the case of multiple inheritance. Additionally, the interface concept is already well-understood by Java programmers. Cons: The Interface suffix lengthens the class name, which can make it harder to read and understand. Also, the interface property may be considered an implementation detail that shouldn't be exposed to clients. Decision: A class may end with Interface only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with Interface. Operator Overloading link ▶Do not overload operators except in rare, special circumstances. Definition: A class can define that operators such as + and / operate on the class as if it were a built-in type. Pros: Can make code appear more intuitive because a class will behave in the same way as built-in types (such as int). Overloaded operators are more playful names for functions that are less-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators. Cons: While operator overloading can make code more intuitive, it has several drawbacks: It can fool our intuition into thinking that expensive operations are cheap, built-in operations. It is much harder to find the call sites for overloaded operators. Searching for Equals() is much easier than searching for relevant invocations of ==. Some operators work on pointers too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 does something totally different. The compiler does not complain for either of these, making this very hard to debug. Overloading also has surprising ramifications. For instance, if a class overloads unary operator&, it cannot safely be forward-declared. Decision: In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the class might be forward-declared. However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container. Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why. See also Copy Constructors and Function Overloading. Access Control link ▶Make data members private, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be protected when using Google Test). Typically a variable would be called foo_ and the accessor function foo(). You may also want a mutator function set_foo(). Exception: static const data members (typically called kFoo) need not be private. The definitions of accessors are usually inlined in the header file. See also Inheritance and Function Names. Declaration Order link ▶Use the specified order of declarations within a class: public: before private:, methods before data members (variables), etc. Your class definition should start with its public: section, followed by its protected: section and then its private: section. If any of these sections are empty, omit them. Within each section, the declarations generally should be in the following order: Typedefs and Enums Constants (static const data members) Constructors Destructor Methods, including static methods Data Members (except static const data members) Friend declarations should always be in the private section, and the DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end of the private: section. It should be the last thing in the class. See Copy Constructors. Method definitions in the corresponding .cc file should be the same as the declaration order, as much as possible. Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details. Write Short Functions link ▶Prefer small and focused functions. We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces. Google-Specific Magic There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere. Smart Pointers link ▶If you actually need pointer semantics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr. "Smart" pointers are objects that act like pointers but have added semantics. When a scoped_ptr is destroyed, for instance, it deletes the object it's pointing to. shared_ptr is the same way, but implements reference-counting so only the last pointer to an object deletes it. Generally speaking, we prefer that we design code with clear object ownership. The clearest object ownership is obtained by using an object directly as a field or local variable, without using pointers at all. On the other extreme, by their very definition, reference counted pointers are owned by nobody. The problem with this design is that it is easy to create circular references or other strange conditions that cause an object to never be deleted. It is also slow to perform atomic operations every time a value is copied or assigned. Although they are not recommended, reference counted pointers are sometimes the simplest and most elegant way to solve a problem. cpplint link ▶Use cpplint.py to detect style errors. cpplint.py is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool. False positives can be ignored by putting // NOLINT at the end of the line. Some projects have instructions on how to run cpplint.py from their project tools. If the project you are contributing to does not, you can download cpplint.py separately. Other C++ Features Reference Arguments link ▶All parameters passed by reference must be labeled const. Definition: In C, if a function needs to modify a variable, the parameter must use a pointer, eg int foo(int *pval). In C++, the function can alternatively declare a reference parameter: int foo(int &val). Pros: Defining a parameter as reference avoids ugly code like (*pval)++. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that NULL is not a possible value. Cons: References can be confusing, as they have value syntax but pointer semantics. Decision: Within function parameter lists all references must be const: void Foo(const string &in, string *out); In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters. One case when you might want an input parameter to be a const pointer is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually best to document this in comments as well. STL adapters such as bind2nd and mem_fun do not permit reference parameters, so you must declare functions with pointer parameters in these cases, too. Function Overloading link ▶Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called. Definition: You may write a function that takes a const string& and overload it with another that takes const char*. class MyClass { public: void Analyze(const string &text); void Analyze(const char *text, size_t textlen); }; Pros: Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors. Cons: If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function. Decision: If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., AppendString(), AppendInt() rather than just Append(). Default Arguments link ▶We do not allow default function parameters, except in a few uncommon situations explained below. Pros: Often you have a function that uses lots of default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Cons: People often figure out how to use an API by looking at existing code that uses it. Default parameters are more difficult to maintain because copy-and-paste from previous code may not reveal all the parameters. Copy-and-pasting of code segments can cause major problems when the default arguments are not appropriate for the new code. Decision: Except as described below, we require all arguments to be explicitly specified, to force programmers to consider the API and the values they are passing for each argument rather than silently accepting defaults they may not be aware of. One specific exception is when default arguments are used to simulate variable-length argument lists. // Support up to 4 params by using a default empty AlphaNum. string StrCat(const AlphaNum &a, const AlphaNum &b = gEmptyAlphaNum, const AlphaNum &c = gEmptyAlphaNum, const AlphaNum &d = gEmptyAlphaNum); Variable-Length Arrays and alloca() link ▶We do not allow variable-length arrays or alloca(). Pros: Variable-length arrays have natural-looking syntax. Both variable-length arrays and alloca() are very efficient. Cons: Variable-length arrays and alloca are not part of Standard C++. More importantly, they allocate a data-dependent amount of stack space that can trigger difficult-to-find memory overwriting bugs: "It ran fine on my machine, but dies mysteriously in production". Decision: Use a safe allocator instead, such as scoped_ptr/scoped_array. Friends link ▶We allow use of friend classes and functions, within reason. Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of friend is to have a FooBuilder class be a friend of Foo so that it can construct the inner state of Foo correctly, without exposing this state to the world. In some cases it may be useful to make a unittest class a friend of the class it tests. Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members. Exceptions link ▶We do not use C++ exceptions. Pros: Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes. Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with. Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries. Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an Init() method, but these require heap allocation or a new "invalid" state, respectively. Exceptions are really handy in testing frameworks. Cons: When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if f() calls g() calls h(), and h throws an exception that f catches, g has to be careful or it may not clean up properly. More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This causes maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand. Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it. Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure. The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these restrictions! Decision: On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions. Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden. Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch. There is an exception to this rule (no pun intended) for Windows code. Run-Time Type Information (RTTI) link ▶We do not use Run Time Type Information (RTTI). Definition: RTTI allows a programmer to query the C++ class of an object at run time. Pros: It is useful in some unittests. For example, it is useful in tests of factory classes where the test has to verify that a newly created object has the expected dynamic type. In rare circumstances, it is useful even outside of tests. Cons: A query of type during run-time typically means a design problem. If you need to know the type of an object at runtime, that is often an indication that you should reconsider the design of your class. Decision: Do not use RTTI, except in unittests. If you find yourself in need of writing code that behaves differently based on the class of an object, consider one of the alternatives to querying the type. Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself. If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system. If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags. Casting link ▶Use C++ casts like static_cast(). Do not use other cast formats like int y = (int)x; or int y = int(x);. Definition: C++ introduced a different cast system from C that distinguishes the types of cast operations. Pros: The problem with C casts is the ambiguity of the operation; sometimes you are doing a conversion (e.g., (int)3.5) and sometimes you are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them. Cons: The syntax is nasty. Decision: Do not use C-style casts. Instead, use these C++-style casts. Use static_cast as the equivalent of a C-style cast that does value conversion, or when you need to explicitly up-cast a pointer from a class to its superclass. Use const_cast to remove the const qualifier (see const). Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues. Do not use dynamic_cast except in test code. If you need to know type information at runtime in this way outside of a unittest, you probably have a design flaw. Streams link ▶Use streams only for logging. Definition: Streams are a replacement for printf() and scanf(). Pros: With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with printf either.) Streams have automatic constructors and destructors that open and close the relevant files. Cons: Streams make it difficult to do functionality like pread(). Some formatting (particularly the common format string idiom %.*s) is difficult if not impossible to do efficiently using streams without using printf-like hacks. Streams do not support operator reordering (the %1s directive), which is helpful for internationalization. Decision: Do not use streams, except where required by a logging interface. Use printf-like routines instead. There are various pros and cons to using streams, but in this case, as in many other cases, consistency trumps the debate. Do not use streams in your code. Extended Discussion There has been debate on this issue, so this explains the reasoning in greater depth. Recall the Only One Way guiding principle: we want to make sure that whenever we do a certain type of I/O, the code looks the same in all those places. Because of this, we do not want to allow users to decide between using streams or using printf plus Read/Write/etc. Instead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons. Proponents of streams have argued that streams are the obvious choice of the two, but the issue is not actually so clear. For every advantage of streams they point out, there is an equivalent disadvantage. The biggest advantage is that you do not need to know the type of the object to be printing. This is a fair point. But, there is a downside: you can easily use the wrong type, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using streams. cout << this; // Prints the address cout << *this; // Prints the contents The compiler does not generate an error because << has been overloaded. We discourage overloading for just this reason. Some say printf formatting is ugly and hard to read, but streams are often no better. Consider the following two fragments, both with the same typo. Which is easier to discover? cerr << "Error connecting to '" <bar()->hostname.first << ":" <bar()->hostname.second << ": " <bar()->hostname.first, foo->bar()->hostname.second, strerror(errno)); And so on and so forth for any issue you might bring up. (You could argue, "Things would be better with the right wrappers," but if it is true for one scheme, is it not also true for the other? Also, remember the goal is to make the language smaller, not add yet more machinery that someone has to learn.) Either path would yield different advantages and disadvantages, and there is not a clearly superior solution. The simplicity doctrine mandates we settle on one of them though, and the majority decision was on printf + read/write. Preincrement and Predecrement link ▶Use prefix form (++i) of the increment and decrement operators with iterators and other template objects. Definition: When a variable is incremented (++i or i++) or decremented (--i or i--) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement). Pros: When the return value is ignored, the "pre" form (++i) is never less efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requires a copy of i to be made, which is the value of the expression. If i is an iterator or other non-scalar type, copying i could be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment? Cons: The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (i) precedes the "verb" (++), just like in English. Decision: For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment. Use of const link ▶We strongly recommend that you use const whenever it makes sense to do so. Definition: Declared variables and parameters can be preceded by the keyword const to indicate the variables are not changed (e.g., const int foo). Class functions can have the const qualifier to indicate the function does not change the state of the class member variables (e.g., class Foo { int Bar(char c) const; };). Pros: Easier for people to understand how variables are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs. Cons: const is viral: if you pass a const variable to a function, that function must have const in its prototype (or the variable will need a const_cast). This can be a particular problem when calling library functions. Decision: const variables, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use const whenever it makes sense to do so: If a function does not modify an argument passed by reference or by pointer, that argument should be const. Declare methods to be const whenever possible. Accessors should almost always be const. Other methods should be const if they do not modify any data members, do not call any non-const methods, and do not return a non-const pointer or non-const reference to a data member. Consider making data members const whenever they do not need to be modified after construction. However, do not go crazy with const. Something like const int * const * const x; is likely overkill, even if it accurately describes how const x is. Focus on what's really useful to know: in this case, const int** x is probably sufficient. The mutable keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first. Where to put the const Some people favor the form int const *foo to const int* foo. They argue that this is more readable because it's more consistent: it keeps the rule that const always follows the object it's describing. However, this consistency argument doesn't apply in this case, because the "don't go crazy" dictum eliminates most of the uses you'd have to be consistent with. Putting the const first is arguably more readable, since it follows English in putting the "adjective" (const) before the "noun" (int). That said, while we encourage putting const first, we do not require it. But be consistent with the code around you! Integer Types link ▶Of the built-in C++ integer types, the only one used is int. If a program needs a variable of a different size, use a precise-width integer type from , such as int16_t. Definition: C++ does not specify the sizes of its integer types. Typically people assume that short is 16 bits, int is 32 bits, long is 32 bits and long long is 64 bits. Pros: Uniformity of declaration. Cons: The sizes of integral types in C++ can vary based on compiler and architecture. Decision: defines types like int16_t, uint32_t, int64_t, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guarantee on the size of an integer. Of the C integer types, only int should be used. When appropriate, you are welcome to use standard types like size_t and ptrdiff_t. We use int very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old int for such things. You should assume that an int is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer type, use int64_t or uint64_t. For integers we know can be "big", use int64_t. You should not use the unsigned integer types such as uint32_t, unless the quantity you are representing is really a bit pattern rather than a number, or unless you need defined twos-complement overflow. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this. On Unsigned Integers Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider: for (unsigned int i = foo.Length()-1; i >= 0; --i) ... This code will never terminate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C's type-promotion scheme causes unsigned types to behave differently than one might expect. So, document that a variable is non-negative using assertions. Don't use an unsigned type. 64-bit Portability link ▶Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and structure alignment. printf() specifiers for some types are not cleanly portable between 32-bit and 64-bit systems. C99 defines some portable format specifiers. Unfortunately, MSVC 7.1 does not understand some of these specifiers and the standard is missing a few, so we have to define our own ugly versions in some cases (in the style of the standard include file inttypes.h): // printf macros for size_t, in the style of inttypes.h #ifdef _LP64 #define __PRIS_PREFIX "z" #else #define __PRIS_PREFIX #endif // Use these macros after a % in a printf format string // to get correct 32/64 bit behavior, like this: // size_t size = records.size(); // printf("%"PRIuS"\n", size); #define PRIdS __PRIS_PREFIX "d" #define PRIxS __PRIS_PREFIX "x" #define PRIuS __PRIS_PREFIX "u" #define PRIXS __PRIS_PREFIX "X" #define PRIoS __PRIS_PREFIX "o" Type DO NOT use DO use Notes void * (or any pointer) %lx %p int64_t %qd, %lld %"PRId64" uint64_t %qu, %llu, %llx %"PRIu64", %"PRIx64" size_t %u %"PRIuS", %"PRIxS" C99 specifies %zu ptrdiff_t %d %"PRIdS" C99 specifies %zd Note that the PRI* macros expand to independent strings which are concatenated by the compiler. Hence if you are using a non-constant format string, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., after the % when using the PRI* macros. So, e.g. printf("x = %30"PRIuS"\n", x) would expand on 32-bit Linux to printf("x = %30" "u" "\n", x), which the compiler will treat as printf("x = %30u\n", x). Remember that sizeof(void *) != sizeof(int). Use intptr_t if you want a pointer-sized integer. You may need to be careful with structure alignments, particularly for structures being stored on disk. Any class/structure with a int64_t/uint64_t member will by default end up being 8-byte aligned on a 64-bit system. If you have such structures being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectures. Most compilers offer a way to alter structure alignment. For gcc, you can use __attribute__((packed)). MSVC offers #pragma pack() and __declspec(align()). Use the LL or ULL suffixes a
DNS解析BIND 9(适用于WINDOWS桌面系统) 完全改进: Security Fixes Treat an all zero netmask as invalid when generating the localnets acl to workaround bug on Windows platform. [CVE-2013-6230] [RT #34687] Fix crashes when serving some NSEC3 signed zones. memcpy was incorrectly called with overlapping ranges, resulting in malformed names being generated on some platforms. This could cause INSIST failures. (CVE 2014-0591) [RT #35120] Features Changes Add the ability to specify ndots to "nslookup". [RT #34711] Introduce a new tool "dnssec-importkey" to allow externally-generated DNSKEY to be imported into the DNSKEY management framework. [RT #34698] Check that EDNS subnet client options are well formed. [RT #34718] "named" now preserves the capitalization of names when responding to queries. [RT #34737] Include a comment in .nzf files (used for adding new zones via "rndc"), giving the name of the associated view. [RT #34765] Use separate rate limiting queues for refresh and notify requests. [RT #30589] Adjust when a master server is deemed unreachable to be less aggressive. [RT #27075] Create delegations for all "children" of empty zones except "forward first". [RT #34826] Changed the name of "isc-config.sh" developers script (for outputting compiler and linker flags) to "bind9-config". [RT #23825] Add "dig" option to keep the TCP socket open between successive queries (+[no]keepopen). [RT #34918] Add dns_client_createx2() function to DNS Client API to provide a way to specify the local address for use when sending update packets. [RT #34811] "named-checkconf -z" now checks zones of type hint as well as master. [RT #35046] Update config.guess and config.sub to add support for ppc64le (powerpc 64-bit Little Endian). [RT #35060] Update the Windows build system to support feature selection and WIN64 builds. This is a work in progress. [RT #34160] Add "dnssec-signzone -Q" switch to drop signatures from keys that are still published but no longer active. [RT #34990] Add a more detailed "not found" message to "rndc" commands which specify a zone name. [RT #35059] named will now warn when a zone's configured "key-directory" does not exist or is not a directory. [RT #35108] Added improvements to statistics channel XSL stylesheet: the stylesheet can now be cached by the browser; section headers are omitted from the stats display when there is no data in those sections to be displayed; counters are now right-justified for easier readability. (Only available with ./configure --enable-newstats.) [RT #35117] "named-checkconf" can now obscure shared secrets when printing by specifying '-x'. [RT #34465] "named" can now accept integer timestamps in RRSIG records. [RT #35185] The export-library API call for loading "resolv.conf", irs_resconf_load(), has been modified to return ISC_R_FILENOTFOUND when the file does not exist and initializes the resconf structure as if the file had existed and configured with nameservers at the localhost addresses (127.0.0.1 and ::1). [RT #35194] Bug Fixes Treat type 65533 (KEYDATA) as opaque except when used in a key zone. [RT #34238] Fix "host" and "nslookup" so don't need dot after the domain by checking ndots when searching. Only continue searching on NXDOMAIN responses. [RT #34711] Handle changes to sig-validity-interval settings better. [RT #34625] Fix bug where journal filename string could be set incorrectly, causing garbage in log messages. [RT #34738] Address a race condition when shutting down a zone. [RT #34750] Address race condition with manual notify requests. [RT #34806] Fix nslookup crash where some readline clones don't accept NULL pointers when calling add_history. [RT #34842] Fix Linux compilation issue when libcap-devel is installed. [RT #34838] Fix installation on Solaris -- don't add explicit make dependencies/rules for python programs as make won't use the implicit rules. [RT #34835] Fix hanging server with inline-signed zones by addressing lock order reversal deadlock with inline zones. [RT #34856] Fix "host" failure if a UDP query timed out. [RT #34870] Address bugs in dns_rdata_fromstruct and dns_rdata_tostruct for WKS and ISDN types. [RT #34910] Updated OpenSSL PKCS#11 patches to fix active list locking and other bugs. [RT #34855] Fix a potential hang with failure to release lock on error in receive_secure_db. #34944] Fix cast in lex.c which could see 0xff treated as EOF. This fixes issue with potential bad data in a database used by DLZ or SDB. [RT #34993] Fix build issue on newer FreeBSD needing -lhx509 for GSSAPI build. [RT #35001] Address read after free in server side of lwres_getrrsetbyname. [RT #29075] Fix "nsupdate" memory leak if "realm" was used multiple times. [RT #35073] Fix "dig" for cleaning up TCP sockets still waiting on connect(). [RT #35074] Fix "dnssec-importkey" so imported key won't overwrite an existing non-imported private key. Fix issue where queries covered by a disabled Response Policy Zone (query type was '*') are answered with TTL of 0. [RT #35026] Fix "nsupdate" memory leak if "realm" was used multiple times. [RT #35073] Fix "dig" for cleaning up TCP sockets still waiting on connect(). [RT #35074] Fix issue with "rndc retransfer" with inline-signing replacing NSEC3 with NSEC records. [RT #34745] Fix issue with "rndc refresh" failing to sign slave zones using inline-signing. [RT #35105] Fix potential hang (detected by our inline-signing system test) with null pointer dereference in libdns zone_xfrdone. [RT #35042] Address bug in libdns loadnode function that could return a freed node on out of memory. [RT #35106] Fixed a bug causing an insecure delegation from one "static-stub" zone to another to fail with a broken trust chain. [RT #35081] Fixed problem where iterative responses could be discarded when the "query-source" port for an upstream query was the same as the listener port (53). [RT #34925] Fix crashes in RBTDB implementation. Two calls to dns_db_getoriginnode were fatal if there was no data at the node. [RT #35080] Fix a possible race and crash in the socket_search() function in dispatch.c. [RT #35107] Fix "dig" so it can handle AXFR style IXFR responses which span multiple messages. [RT #35137] Fix a "host" tool problem with converting UTF-8 textname to IDN encoding by handling "." as a search list element when IDN support is enabled. [RT #35133] Fix "queryperf" to prevent a possible integer overflow when printing results. [RT #35182] Prevent a theoretically possible race and crash when obtaining a socket in dispatch.c [RT #35128] Use built-in versions of strptime() and timegm() on all platforms to avoid portability issues. [RT #35183] Fix a bug which could cause a crash when running "rndc reconfig" or "rndc reload" after configuration is changed from regular zones to automatic empty zones. [RT #35177]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsdhla

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值