Returns Java major version, such as 8, 11, or 17.
| 319 | |
| 320 | // Returns Java major version, such as 8, 11, or 17. |
| 321 | static int GetJavaMajorVersion() { |
| 322 | string cmd = "java"; |
| 323 | const char* java_home = getenv("JAVA_HOME"); |
| 324 | if (java_home != NULL) { |
| 325 | cmd = (filesystem::path(java_home) / "bin" / "java").string(); |
| 326 | } |
| 327 | cmd += " -version 2>&1"; |
| 328 | string msg; |
| 329 | if (!RunShellProcess(cmd, &msg, false, {"JAVA_TOOL_OPTIONS"})) { |
| 330 | LOG(INFO) << Substitute("Unable to determine Java version (default to 8): $0", msg); |
| 331 | return 8; |
| 332 | } |
| 333 | |
| 334 | // Find a version string in the first line. |
| 335 | string first_line; |
| 336 | std::getline(istringstream(msg), first_line); |
| 337 | // Need to allow for a wide variety of formats for different JDK implementations. |
| 338 | // Example: openjdk version "11.0.19" 2023-04-18 |
| 339 | std::regex java_version_pattern("\"([0-9]{1,3})\\.[0-9]+\\.[0-9]+[^\"]*\""); |
| 340 | std::smatch matches; |
| 341 | if (!std::regex_search(first_line, matches, java_version_pattern)) { |
| 342 | LOG(INFO) << Substitute("Unable to determine Java version (default to 8): $0", msg); |
| 343 | return 8; |
| 344 | } |
| 345 | DCHECK_EQ(matches.size(), 2); |
| 346 | return std::stoi(matches.str(1)); |
| 347 | } |
| 348 | |
| 349 | // Append the javaagent arg to JAVA_TOOL_OPTIONS to load jamm. |
| 350 | static Status JavaAddJammAgent() { |
no test coverage detected