re PR rtl-optimization/89795 (wrong code with -O2 -fno-dce -fno-forward-propagate...
[official-gcc.git] / libcc1 / findcomp.cc
blob6507269ed69b63cf1e067eef406f03fc8e5248ad
1 /* Find the correct compiler.
2 Copyright (C) 2014-2019 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include <config.h>
21 #include <string>
22 #include <dirent.h>
23 #include <stdlib.h>
25 #include "libiberty.h"
26 #include "xregex.h"
27 #include "findcomp.hh"
28 #include "system.h"
30 class scanner
32 public:
34 scanner (const std::string &dir)
36 m_dir = opendir (dir.c_str ());
39 ~scanner ()
41 if (m_dir != NULL)
42 closedir (m_dir);
45 const char *next ()
47 if (m_dir == NULL)
48 return NULL;
50 struct dirent *entry = readdir (m_dir);
51 if (entry == NULL)
52 return NULL;
54 return entry->d_name;
57 private:
59 DIR *m_dir;
62 static bool
63 search_dir (const regex_t &regexp, const std::string &dir, std::string *result)
65 scanner scan (dir);
66 const char *filename;
68 while ((filename = scan.next ()) != NULL)
70 if (regexec (&regexp, filename, 0, NULL, 0) == 0)
72 *result = dir + DIR_SEPARATOR + filename;
73 return true;
77 return false;
80 class tokenizer
82 public:
84 tokenizer (const char *str)
85 : m_str (str),
86 m_pos (0)
90 bool done () const
92 return m_pos == std::string::npos;
95 std::string next ()
97 std::string::size_type last_pos = m_pos;
98 std::string::size_type colon = m_str.find(':', last_pos);
100 std::string result;
101 if (colon == std::string::npos)
103 m_pos = colon;
104 result = m_str.substr(last_pos, colon);
106 else
108 m_pos = colon + 1;
109 result = m_str.substr(last_pos, colon - last_pos);
111 if (result == "")
112 result = ".";
114 return result;
117 private:
119 std::string m_str;
120 std::string::size_type m_pos;
123 bool
124 find_compiler (const regex_t &regexp, std::string *result)
126 const char *cpath = getenv ("PATH");
128 if (cpath == NULL)
129 return false;
131 tokenizer dirs (cpath);
132 while (!dirs.done ())
134 std::string dir = dirs.next ();
135 if (search_dir (regexp, dir, result))
136 return true;
139 return false;