message.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. // Copyright (C) 2011, 2015 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <cctype>
  15. #include <cstddef>
  16. #include <fstream>
  17. #include <iostream>
  18. #include <string>
  19. #include <vector>
  20. #include <errno.h>
  21. #include <getopt.h>
  22. #include <string.h>
  23. #include <time.h>
  24. #include <unistd.h>
  25. #include <exceptions/exceptions.h>
  26. #include <util/filename.h>
  27. #include <util/strutil.h>
  28. #include <log/log_messages.h>
  29. #include <log/message_dictionary.h>
  30. #include <log/message_exception.h>
  31. #include <log/message_reader.h>
  32. #include <log/logger.h>
  33. #include <boost/foreach.hpp>
  34. using namespace std;
  35. using namespace isc::log;
  36. using namespace isc::util;
  37. static const char* VERSION = "1.0-0";
  38. /// \file log/compiler/message.cc
  39. /// \brief Message Compiler
  40. ///
  41. /// \b Overview<BR>
  42. /// This is the program that takes as input a message file and produces:
  43. ///
  44. /// \li A .h file containing message definition
  45. /// \li A .cc file containing code that adds the messages to the program's
  46. /// message dictionary at start-up time.
  47. ///
  48. /// \b Invocation<BR>
  49. /// The program is invoked with the command:
  50. ///
  51. /// <tt>message [-v | -h | -d &lt;dir&gt; | <message-file>]</tt>
  52. ///
  53. /// It reads the message file and writes out two files of the same
  54. /// name in the current working directory (unless -d is used) but
  55. /// with extensions of .h and .cc.
  56. ///
  57. /// -v causes it to print the version number and exit. -h prints a
  58. /// help message (and exits). -d &lt;dir&gt; will make it write the
  59. /// output file(s) to dir instead of current working directory
  60. /// \brief Print Version
  61. ///
  62. /// Prints the program's version number.
  63. void
  64. version() {
  65. cout << VERSION << "\n";
  66. }
  67. /// \brief Print Usage
  68. ///
  69. /// Prints program usage to stdout.
  70. void
  71. usage() {
  72. cout <<
  73. "Usage: message [-h] [-v] [-d dir] <message-file>\n" <<
  74. "\n" <<
  75. "-h Print this message and exit\n" <<
  76. "-v Print the program version and exit\n" <<
  77. "-d <dir> Place output files in given directory\n" <<
  78. "\n" <<
  79. "<message-file> is the name of the input message file.\n";
  80. }
  81. /// \brief Create Time
  82. ///
  83. /// Returns the current time as a suitably-formatted string.
  84. ///
  85. /// \return Current time
  86. string
  87. currentTime() {
  88. // Get a text representation of the current time.
  89. time_t curtime;
  90. time(&curtime);
  91. struct tm* timeinfo;
  92. timeinfo = localtime(&curtime);
  93. char buffer[80];
  94. strftime(buffer, 80, "%a %b %d %Y %H:%M", timeinfo);
  95. return (std::string(buffer));
  96. }
  97. /// \brief Create Header Sentinel
  98. ///
  99. /// Given the name of a file, create an \#ifdef sentinel name. The name is
  100. /// &lt;name&gt;_&lt;ext&gt;, where &lt;name&gt; is the name of the file, and &lt;ext&gt;
  101. /// is the extension less the leading period. The sentinel will be upper-case.
  102. ///
  103. /// \param file Filename object representing the file.
  104. ///
  105. /// \return Sentinel name
  106. string
  107. sentinel(Filename& file) {
  108. string name = file.name();
  109. string ext = file.extension();
  110. string sentinel_text = name + "_" + ext.substr(1);
  111. isc::util::str::uppercase(sentinel_text);
  112. return (sentinel_text);
  113. }
  114. /// \brief Quote String
  115. ///
  116. /// Inserts an escape character (a backslash) prior to any double quote
  117. /// characters. This is used to handle the fact that the input file does not
  118. /// contain quotes, yet the string will be included in a C++ literal string.
  119. string
  120. quoteString(const string& instring) {
  121. // Create the output string and reserve the space needed to hold the input
  122. // string. (Most input strings will not contain quotes, so this single
  123. // reservation should be all that is needed.)
  124. string outstring;
  125. outstring.reserve(instring.size());
  126. // Iterate through the input string, preceding quotes with a slash.
  127. for (size_t i = 0; i < instring.size(); ++i) {
  128. if (instring[i] == '"') {
  129. outstring += '\\';
  130. }
  131. outstring += instring[i];
  132. }
  133. return (outstring);
  134. }
  135. /// \brief Sorted Identifiers
  136. ///
  137. /// Given a dictionary, return a vector holding the message IDs in sorted
  138. /// order.
  139. ///
  140. /// \param dictionary Dictionary to examine
  141. ///
  142. /// \return Sorted list of message IDs
  143. vector<string>
  144. sortedIdentifiers(MessageDictionary& dictionary) {
  145. vector<string> ident;
  146. for (MessageDictionary::const_iterator i = dictionary.begin();
  147. i != dictionary.end(); ++i) {
  148. ident.push_back(i->first);
  149. }
  150. sort(ident.begin(), ident.end());
  151. return (ident);
  152. }
  153. /// \brief Split Namespace
  154. ///
  155. /// The $NAMESPACE directive may well specify a namespace in the form a::b.
  156. /// Unfortunately, the C++ "namespace" statement can only accept a single
  157. /// string - to set up the namespace of "a::b" requires two statements, one
  158. /// for "namespace a" and the other for "namespace b".
  159. ///
  160. /// This function returns the set of namespace components as a vector of
  161. /// strings. A vector of one element, containing the empty string, is returned
  162. /// if the anonymous namespace is specified.
  163. ///
  164. /// \param ns Argument to $NAMESPACE (passed by value, as we will be modifying
  165. /// it.)
  166. vector<string>
  167. splitNamespace(string ns) {
  168. // Namespaces components are separated by double colon characters -
  169. // convert to single colons.
  170. size_t dcolon;
  171. while ((dcolon = ns.find("::")) != string::npos) {
  172. ns.replace(dcolon, 2, ":");
  173. }
  174. // ... and return the vector of namespace components split on the single
  175. // colon.
  176. return (isc::util::str::tokens(ns, ":"));
  177. }
  178. /// \brief Write Opening Namespace(s)
  179. ///
  180. /// Writes the lines listing the namespaces in use.
  181. void
  182. writeOpeningNamespace(ostream& output, const vector<string>& ns) {
  183. if (!ns.empty()) {
  184. // Output namespaces in correct order
  185. for (vector<string>::size_type i = 0; i < ns.size(); ++i) {
  186. output << "namespace " << ns[i] << " {\n";
  187. }
  188. output << "\n";
  189. }
  190. }
  191. /// \brief Write Closing Namespace(s)
  192. ///
  193. /// Writes the lines listing the namespaces in use.
  194. void
  195. writeClosingNamespace(ostream& output, const vector<string>& ns) {
  196. if (!ns.empty()) {
  197. for (int i = ns.size() - 1; i >= 0; --i) {
  198. output << "} // namespace " << ns[i] << "\n";
  199. }
  200. output << "\n";
  201. }
  202. }
  203. /// \brief Write Header File
  204. ///
  205. /// Writes the C++ header file containing the symbol definitions. These are
  206. /// "extern" references to definitions in the .cc file. As such, they should
  207. /// take up no space in the module in which they are included, and redundant
  208. /// references should be removed by the compiler.
  209. ///
  210. /// \param file Name of the message file. The header file is written to a
  211. /// file of the same name but with a .h suffix.
  212. /// \param ns_components Namespace in which the definitions are to be placed.
  213. /// An empty string indicates no namespace.
  214. /// \param dictionary Dictionary holding the message definitions.
  215. /// \param output_directory if not null NULL, output files are written
  216. /// to the given directory. If NULL, they are written to the current
  217. /// working directory.
  218. void
  219. writeHeaderFile(const string& file, const vector<string>& ns_components,
  220. MessageDictionary& dictionary, const char* output_directory)
  221. {
  222. Filename message_file(file);
  223. Filename header_file(Filename(message_file.name()).useAsDefault(".h"));
  224. if (output_directory != NULL) {
  225. header_file.setDirectory(output_directory);
  226. }
  227. // Text to use as the sentinels.
  228. string sentinel_text = sentinel(header_file);
  229. // Open the output file for writing
  230. ofstream hfile(header_file.fullName().c_str());
  231. if (hfile.fail()) {
  232. isc_throw_4(MessageException, "Failed to open output file",
  233. LOG_OPEN_OUTPUT_FAIL, header_file.fullName(),
  234. strerror(errno), 0);
  235. }
  236. // Write the header preamble. If there is an error, we'll pick it up
  237. // after the last write.
  238. hfile <<
  239. "// File created from " << message_file.fullName() << " on " <<
  240. currentTime() << "\n" <<
  241. "\n" <<
  242. "#ifndef " << sentinel_text << "\n" <<
  243. "#define " << sentinel_text << "\n" <<
  244. "\n" <<
  245. "#include <log/message_types.h>\n" <<
  246. "\n";
  247. // Write the message identifiers, bounded by a namespace declaration
  248. writeOpeningNamespace(hfile, ns_components);
  249. vector<string> idents = sortedIdentifiers(dictionary);
  250. for (vector<string>::const_iterator j = idents.begin();
  251. j != idents.end(); ++j) {
  252. hfile << "extern const isc::log::MessageID " << *j << ";\n";
  253. }
  254. hfile << "\n";
  255. writeClosingNamespace(hfile, ns_components);
  256. // ... and finally the postamble
  257. hfile << "#endif // " << sentinel_text << "\n";
  258. // Report errors (if any) and exit
  259. if (hfile.fail()) {
  260. isc_throw_4(MessageException, "Error writing to output file",
  261. LOG_WRITE_ERROR, header_file.fullName(), strerror(errno),
  262. 0);
  263. }
  264. hfile.close();
  265. }
  266. /// \brief Convert Non Alpha-Numeric Characters to Underscores
  267. ///
  268. /// Simple function for use in a call to transform
  269. char
  270. replaceNonAlphaNum(char c) {
  271. return (isalnum(c) ? c : '_');
  272. }
  273. /// \brief Write Program File
  274. ///
  275. /// Writes the C++ source code file. This defines the text of the message
  276. /// symbols, as well as the initializer object that sets the entries in the
  277. /// global dictionary.
  278. ///
  279. /// The construction of the initializer object loads the dictionary with the
  280. /// message text. However, nothing actually references it. If the initializer
  281. /// were in a file by itself, the lack of things referencing it would cause the
  282. /// linker to ignore it when pulling modules out of the logging library in a
  283. /// static link. By including it in the file with the symbol definitions, the
  284. /// module will get included in the link process to resolve the symbol
  285. /// definitions, and so the initializer object will be included in the final
  286. /// image. (Note that there are no such problems when the logging library is
  287. /// built as a dynamically-linked library: the whole library - including the
  288. /// initializer module - gets mapped into address space when the library is
  289. /// loaded, after which all the initializing code (including the constructors
  290. /// of objects declared outside functions) gets run.)
  291. ///
  292. /// There _may_ be a problem when we come to port this to Windows. Microsoft
  293. /// Visual Studio contains a "Whole Program Optimization" option, where the
  294. /// optimization is done at link-time, not compiler-time. In this it _may_
  295. /// decide to remove the initializer object because of a lack of references
  296. /// to it. But until BIND-10 is ported to Windows, we won't know.
  297. ///
  298. /// \param file Name of the message file. The header file is written to a
  299. /// file of the same name but with a .h suffix.
  300. /// \param ns_components Namespace in which the definitions are to be placed.
  301. /// An empty string indicates no namespace.
  302. /// \param dictionary Dictionary holding the message definitions.
  303. /// \param output_directory if not null NULL, output files are written
  304. /// to the given directory. If NULL, they are written to the current
  305. /// working directory.
  306. void
  307. writeProgramFile(const string& file, const vector<string>& ns_components,
  308. MessageDictionary& dictionary,
  309. const char* output_directory)
  310. {
  311. Filename message_file(file);
  312. Filename program_file(Filename(message_file.name()).useAsDefault(".cc"));
  313. if (output_directory) {
  314. program_file.setDirectory(output_directory);
  315. }
  316. // Open the output file for writing
  317. ofstream ccfile(program_file.fullName().c_str());
  318. if (ccfile.fail()) {
  319. isc_throw_4(MessageException, "Error opening output file",
  320. LOG_OPEN_OUTPUT_FAIL, program_file.fullName(),
  321. strerror(errno), 0);
  322. }
  323. // Write the preamble. If there is an error, we'll pick it up after
  324. // the last write.
  325. ccfile <<
  326. "// File created from " << message_file.fullName() << " on " <<
  327. currentTime() << "\n" <<
  328. "\n" <<
  329. "#include <cstddef>\n" <<
  330. "#include <log/message_types.h>\n" <<
  331. "#include <log/message_initializer.h>\n" <<
  332. "\n";
  333. // Declare the message symbols themselves.
  334. writeOpeningNamespace(ccfile, ns_components);
  335. vector<string> idents = sortedIdentifiers(dictionary);
  336. for (vector<string>::const_iterator j = idents.begin();
  337. j != idents.end(); ++j) {
  338. ccfile << "extern const isc::log::MessageID " << *j <<
  339. " = \"" << *j << "\";\n";
  340. }
  341. ccfile << "\n";
  342. writeClosingNamespace(ccfile, ns_components);
  343. // Now the code for the message initialization.
  344. ccfile <<
  345. "namespace {\n" <<
  346. "\n" <<
  347. "const char* values[] = {\n";
  348. // Output the identifiers and the associated text.
  349. idents = sortedIdentifiers(dictionary);
  350. for (vector<string>::const_iterator i = idents.begin();
  351. i != idents.end(); ++i) {
  352. ccfile << " \"" << *i << "\", \"" <<
  353. quoteString(dictionary.getText(*i)) << "\",\n";
  354. }
  355. // ... and the postamble
  356. ccfile <<
  357. " NULL\n" <<
  358. "};\n" <<
  359. "\n" <<
  360. "const isc::log::MessageInitializer initializer(values);\n" <<
  361. "\n" <<
  362. "} // Anonymous namespace\n" <<
  363. "\n";
  364. // Report errors (if any) and exit
  365. if (ccfile.fail()) {
  366. isc_throw_4(MessageException, "Error writing to output file",
  367. LOG_WRITE_ERROR, program_file.fullName(), strerror(errno),
  368. 0);
  369. }
  370. ccfile.close();
  371. }
  372. /// \brief Error and exit if there are duplicate entries
  373. ///
  374. /// If the input file contained duplicate message IDs, we print an
  375. /// error for each of them, then exit the program with a non-0 value.
  376. ///
  377. /// \param reader Message Reader used to read the file
  378. void
  379. errorDuplicates(MessageReader& reader) {
  380. // Get the duplicates (the overflow) and, if present, sort them into some
  381. // order and remove those which occur more than once (which mean that they
  382. // occur more than twice in the input file).
  383. MessageReader::MessageIDCollection duplicates = reader.getNotAdded();
  384. if (!duplicates.empty()) {
  385. cout << "Error: the following duplicate IDs were found:\n";
  386. sort(duplicates.begin(), duplicates.end());
  387. MessageReader::MessageIDCollection::iterator new_end =
  388. unique(duplicates.begin(), duplicates.end());
  389. for (MessageReader::MessageIDCollection::iterator i = duplicates.begin();
  390. i != new_end; ++i) {
  391. cout << " " << *i << "\n";
  392. }
  393. exit(1);
  394. }
  395. }
  396. /// \brief Main Program
  397. ///
  398. /// Parses the options then dispatches to the appropriate function. See the
  399. /// main file header for the invocation.
  400. int
  401. main(int argc, char* argv[]) {
  402. const char* soptions = "hvpd:"; // Short options
  403. optind = 1; // Ensure we start a new scan
  404. int opt; // Value of the option
  405. const char *output_directory = NULL;
  406. while ((opt = getopt(argc, argv, soptions)) != -1) {
  407. switch (opt) {
  408. case 'd':
  409. output_directory = optarg;
  410. break;
  411. case 'h':
  412. usage();
  413. return (0);
  414. case 'v':
  415. version();
  416. return (0);
  417. default:
  418. // A message will have already been output about the error.
  419. return (1);
  420. }
  421. }
  422. // Do we have the message file?
  423. if (optind < (argc - 1)) {
  424. cout << "Error: excess arguments in command line\n";
  425. usage();
  426. return (1);
  427. } else if (optind >= argc) {
  428. cout << "Error: missing message file\n";
  429. usage();
  430. return (1);
  431. }
  432. string message_file = argv[optind];
  433. try {
  434. // Have identified the file, so process it. First create a local
  435. // dictionary into which the data will be put.
  436. MessageDictionary dictionary;
  437. // Read the data into it.
  438. MessageReader reader(&dictionary);
  439. reader.readFile(message_file);
  440. // Error (and quit) if there are of any duplicates encountered.
  441. errorDuplicates(reader);
  442. // Get the namespace into which the message definitions will be put and
  443. // split it into components.
  444. vector<string> ns_components =
  445. splitNamespace(reader.getNamespace());
  446. // Write the header file.
  447. writeHeaderFile(message_file, ns_components, dictionary,
  448. output_directory);
  449. // Write the file that defines the message symbols and text
  450. writeProgramFile(message_file, ns_components, dictionary,
  451. output_directory);
  452. }
  453. catch (const MessageException& e) {
  454. // Create an error message from the ID and the text
  455. const MessageDictionaryPtr& global = MessageDictionary::globalDictionary();
  456. string text = e.id();
  457. text += ", ";
  458. text += global->getText(e.id());
  459. // Format with arguments
  460. vector<string> args(e.arguments());
  461. for (size_t i(0); i < args.size(); ++ i) {
  462. replacePlaceholder(&text, args[i], i + 1);
  463. }
  464. cerr << text << "\n";
  465. return (1);
  466. }
  467. return (0);
  468. }