GraphWriter.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. //===- GraphWriter.cpp - Implements GraphWriter support routines ----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements misc. GraphWriter support routines.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Support/GraphWriter.h"
  13. #include "DebugOptions.h"
  14. #include "llvm/ADT/SmallString.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/Config/config.h"
  18. #include "llvm/Support/Compiler.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include "llvm/Support/ErrorOr.h"
  21. #include "llvm/Support/FileSystem.h"
  22. #include "llvm/Support/Path.h"
  23. #include "llvm/Support/Program.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #ifdef __APPLE__
  26. #include "llvm/Support/CommandLine.h"
  27. #endif
  28. #include <string>
  29. #include <system_error>
  30. #include <vector>
  31. using namespace llvm;
  32. #ifdef __APPLE__
  33. namespace {
  34. struct CreateViewBackground {
  35. static void *call() {
  36. return new cl::opt<bool>("view-background", cl::Hidden,
  37. cl::desc("Execute graph viewer in the background. "
  38. "Creates tmp file litter."));
  39. }
  40. };
  41. } // namespace
  42. static ManagedStatic<cl::opt<bool>, CreateViewBackground> ViewBackground;
  43. void llvm::initGraphWriterOptions() { *ViewBackground; }
  44. #else
  45. void llvm::initGraphWriterOptions() {}
  46. #endif
  47. std::string llvm::DOT::EscapeString(const std::string &Label) {
  48. std::string Str(Label);
  49. for (unsigned i = 0; i != Str.length(); ++i)
  50. switch (Str[i]) {
  51. case '\n':
  52. Str.insert(Str.begin()+i, '\\'); // Escape character...
  53. ++i;
  54. Str[i] = 'n';
  55. break;
  56. case '\t':
  57. Str.insert(Str.begin()+i, ' '); // Convert to two spaces
  58. ++i;
  59. Str[i] = ' ';
  60. break;
  61. case '\\':
  62. if (i+1 != Str.length())
  63. switch (Str[i+1]) {
  64. case 'l': continue; // don't disturb \l
  65. case '|': case '{': case '}':
  66. Str.erase(Str.begin()+i); continue;
  67. default: break;
  68. }
  69. [[fallthrough]];
  70. case '{': case '}':
  71. case '<': case '>':
  72. case '|': case '"':
  73. Str.insert(Str.begin()+i, '\\'); // Escape character...
  74. ++i; // don't infinite loop
  75. break;
  76. }
  77. return Str;
  78. }
  79. /// Get a color string for this node number. Simply round-robin selects
  80. /// from a reasonable number of colors.
  81. StringRef llvm::DOT::getColorString(unsigned ColorNumber) {
  82. static const int NumColors = 20;
  83. static const char* Colors[NumColors] = {
  84. "aaaaaa", "aa0000", "00aa00", "aa5500", "0055ff", "aa00aa", "00aaaa",
  85. "555555", "ff5555", "55ff55", "ffff55", "5555ff", "ff55ff", "55ffff",
  86. "ffaaaa", "aaffaa", "ffffaa", "aaaaff", "ffaaff", "aaffff"};
  87. return Colors[ColorNumber % NumColors];
  88. }
  89. static std::string replaceIllegalFilenameChars(std::string Filename,
  90. const char ReplacementChar) {
  91. std::string IllegalChars =
  92. is_style_windows(sys::path::Style::native) ? "\\/:?\"<>|" : "/";
  93. for (char IllegalChar : IllegalChars) {
  94. std::replace(Filename.begin(), Filename.end(), IllegalChar,
  95. ReplacementChar);
  96. }
  97. return Filename;
  98. }
  99. std::string llvm::createGraphFilename(const Twine &Name, int &FD) {
  100. FD = -1;
  101. SmallString<128> Filename;
  102. // Windows can't always handle long paths, so limit the length of the name.
  103. std::string N = Name.str();
  104. N = N.substr(0, std::min<std::size_t>(N.size(), 140));
  105. // Replace illegal characters in graph Filename with '_' if needed
  106. std::string CleansedName = replaceIllegalFilenameChars(N, '_');
  107. std::error_code EC =
  108. sys::fs::createTemporaryFile(CleansedName, "dot", FD, Filename);
  109. if (EC) {
  110. errs() << "Error: " << EC.message() << "\n";
  111. return "";
  112. }
  113. errs() << "Writing '" << Filename << "'... ";
  114. return std::string(Filename.str());
  115. }
  116. // Execute the graph viewer. Return true if there were errors.
  117. static bool ExecGraphViewer(StringRef ExecPath, std::vector<StringRef> &args,
  118. StringRef Filename, bool wait,
  119. std::string &ErrMsg) {
  120. if (wait) {
  121. if (sys::ExecuteAndWait(ExecPath, args, std::nullopt, {}, 0, 0, &ErrMsg)) {
  122. errs() << "Error: " << ErrMsg << "\n";
  123. return true;
  124. }
  125. sys::fs::remove(Filename);
  126. errs() << " done. \n";
  127. } else {
  128. sys::ExecuteNoWait(ExecPath, args, std::nullopt, {}, 0, &ErrMsg);
  129. errs() << "Remember to erase graph file: " << Filename << "\n";
  130. }
  131. return false;
  132. }
  133. namespace {
  134. struct GraphSession {
  135. std::string LogBuffer;
  136. bool TryFindProgram(StringRef Names, std::string &ProgramPath) {
  137. raw_string_ostream Log(LogBuffer);
  138. SmallVector<StringRef, 8> parts;
  139. Names.split(parts, '|');
  140. for (auto Name : parts) {
  141. if (ErrorOr<std::string> P = sys::findProgramByName(Name)) {
  142. ProgramPath = *P;
  143. return true;
  144. }
  145. Log << " Tried '" << Name << "'\n";
  146. }
  147. return false;
  148. }
  149. };
  150. } // end anonymous namespace
  151. static const char *getProgramName(GraphProgram::Name program) {
  152. switch (program) {
  153. case GraphProgram::DOT:
  154. return "dot";
  155. case GraphProgram::FDP:
  156. return "fdp";
  157. case GraphProgram::NEATO:
  158. return "neato";
  159. case GraphProgram::TWOPI:
  160. return "twopi";
  161. case GraphProgram::CIRCO:
  162. return "circo";
  163. }
  164. llvm_unreachable("bad kind");
  165. }
  166. bool llvm::DisplayGraph(StringRef FilenameRef, bool wait,
  167. GraphProgram::Name program) {
  168. std::string Filename = std::string(FilenameRef);
  169. std::string ErrMsg;
  170. std::string ViewerPath;
  171. GraphSession S;
  172. #ifdef __APPLE__
  173. wait &= !*ViewBackground;
  174. if (S.TryFindProgram("open", ViewerPath)) {
  175. std::vector<StringRef> args;
  176. args.push_back(ViewerPath);
  177. if (wait)
  178. args.push_back("-W");
  179. args.push_back(Filename);
  180. errs() << "Trying 'open' program... ";
  181. if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg))
  182. return false;
  183. }
  184. #endif
  185. if (S.TryFindProgram("xdg-open", ViewerPath)) {
  186. std::vector<StringRef> args;
  187. args.push_back(ViewerPath);
  188. args.push_back(Filename);
  189. errs() << "Trying 'xdg-open' program... ";
  190. if (!ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg))
  191. return false;
  192. }
  193. // Graphviz
  194. if (S.TryFindProgram("Graphviz", ViewerPath)) {
  195. std::vector<StringRef> args;
  196. args.push_back(ViewerPath);
  197. args.push_back(Filename);
  198. errs() << "Running 'Graphviz' program... ";
  199. return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  200. }
  201. // xdot
  202. if (S.TryFindProgram("xdot|xdot.py", ViewerPath)) {
  203. std::vector<StringRef> args;
  204. args.push_back(ViewerPath);
  205. args.push_back(Filename);
  206. args.push_back("-f");
  207. args.push_back(getProgramName(program));
  208. errs() << "Running 'xdot.py' program... ";
  209. return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  210. }
  211. enum ViewerKind {
  212. VK_None,
  213. VK_OSXOpen,
  214. VK_XDGOpen,
  215. VK_Ghostview,
  216. VK_CmdStart
  217. };
  218. ViewerKind Viewer = VK_None;
  219. #ifdef __APPLE__
  220. if (!Viewer && S.TryFindProgram("open", ViewerPath))
  221. Viewer = VK_OSXOpen;
  222. #endif
  223. if (!Viewer && S.TryFindProgram("gv", ViewerPath))
  224. Viewer = VK_Ghostview;
  225. if (!Viewer && S.TryFindProgram("xdg-open", ViewerPath))
  226. Viewer = VK_XDGOpen;
  227. #ifdef _WIN32
  228. if (!Viewer && S.TryFindProgram("cmd", ViewerPath)) {
  229. Viewer = VK_CmdStart;
  230. }
  231. #endif
  232. // PostScript or PDF graph generator + PostScript/PDF viewer
  233. std::string GeneratorPath;
  234. if (Viewer &&
  235. (S.TryFindProgram(getProgramName(program), GeneratorPath) ||
  236. S.TryFindProgram("dot|fdp|neato|twopi|circo", GeneratorPath))) {
  237. std::string OutputFilename =
  238. Filename + (Viewer == VK_CmdStart ? ".pdf" : ".ps");
  239. std::vector<StringRef> args;
  240. args.push_back(GeneratorPath);
  241. if (Viewer == VK_CmdStart)
  242. args.push_back("-Tpdf");
  243. else
  244. args.push_back("-Tps");
  245. args.push_back("-Nfontname=Courier");
  246. args.push_back("-Gsize=7.5,10");
  247. args.push_back(Filename);
  248. args.push_back("-o");
  249. args.push_back(OutputFilename);
  250. errs() << "Running '" << GeneratorPath << "' program... ";
  251. if (ExecGraphViewer(GeneratorPath, args, Filename, true, ErrMsg))
  252. return true;
  253. // The lifetime of StartArg must include the call of ExecGraphViewer
  254. // because the args are passed as vector of char*.
  255. std::string StartArg;
  256. args.clear();
  257. args.push_back(ViewerPath);
  258. switch (Viewer) {
  259. case VK_OSXOpen:
  260. args.push_back("-W");
  261. args.push_back(OutputFilename);
  262. break;
  263. case VK_XDGOpen:
  264. wait = false;
  265. args.push_back(OutputFilename);
  266. break;
  267. case VK_Ghostview:
  268. args.push_back("--spartan");
  269. args.push_back(OutputFilename);
  270. break;
  271. case VK_CmdStart:
  272. args.push_back("/S");
  273. args.push_back("/C");
  274. StartArg =
  275. (StringRef("start ") + (wait ? "/WAIT " : "") + OutputFilename).str();
  276. args.push_back(StartArg);
  277. break;
  278. case VK_None:
  279. llvm_unreachable("Invalid viewer");
  280. }
  281. ErrMsg.clear();
  282. return ExecGraphViewer(ViewerPath, args, OutputFilename, wait, ErrMsg);
  283. }
  284. // dotty
  285. if (S.TryFindProgram("dotty", ViewerPath)) {
  286. std::vector<StringRef> args;
  287. args.push_back(ViewerPath);
  288. args.push_back(Filename);
  289. // Dotty spawns another app and doesn't wait until it returns
  290. #ifdef _WIN32
  291. wait = false;
  292. #endif
  293. errs() << "Running 'dotty' program... ";
  294. return ExecGraphViewer(ViewerPath, args, Filename, wait, ErrMsg);
  295. }
  296. errs() << "Error: Couldn't find a usable graph viewer program:\n";
  297. errs() << S.LogBuffer << "\n";
  298. return true;
  299. }