-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
JNetReflectorHelper.cs
221 lines (204 loc) · 9.83 KB
/
JNetReflectorHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/*
* Copyright 2024 MASES s.r.l.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Refer to LICENSE for more information.
*/
/*
* This file is generated by MASES.JNetReflector (ver. 1.5.1.0)
* using rt.jar as reference
*/
using Java.Lang;
using Java.Util;
using MASES.JCOBridge.C2JBridge;
using MASES.JNetReflector;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Org.Mases.Jnet
{
/// <summary>
/// An helper class to manage the Java class JNetReflectorHelper
/// </summary>
public class JNetReflectorHelper : JVMBridgeBase<JNetReflectorHelper>
{
static string JNetReflectorHelperTempFolder = Path.Combine(Path.GetDirectoryName(typeof(JNetReflectorHelper).Assembly.Location));
public override string BridgeClassName => "org.mases.jnet.developed.JNetReflectorHelper";
/// <summary>
/// Enable or disable logging
/// </summary>
public static bool EnableLogging
{
get { return SExecute<bool>("getLoggingState"); }
set { SExecute("setLoggingState", value); }
}
public static IDictionary<Class, IReadOnlyDictionary<string, string>> ExtractJavaInfo(IEnumerable<Class> classes, string classPath, string javapFullPath = null)
{
const int argumentLengthLimit = 32699; // from MSDN
List<Class> localList = new List<Class>(classes);
var dict = new ConcurrentDictionary<Class, IReadOnlyDictionary<string, string>>();
string baseArgumentStr = string.IsNullOrWhiteSpace(classPath) ? string.Empty : $"-cp {classPath} " + "-s ";
if (baseArgumentStr.Length > argumentLengthLimit)
{
throw new ArgumentException("The length is too long to fill in the available storage", nameof(classPath));
}
while (localList.Count != 0)
{
List<Class> toBeAnalyzed = new();
string arguments = (string.IsNullOrWhiteSpace(classPath) ? string.Empty : $"-cp {classPath} ") + "-s ";
foreach (var clazz in localList.ToArray())
{
string newClass = $"{clazz.Name} ";
int newLength = arguments.Length + newClass.Length;
if (newLength < argumentLengthLimit)
{
arguments += newClass;
toBeAnalyzed.Add(clazz);
localList.Remove(clazz);
}
else break;
}
Process process = null;
bool exited = false;
try
{
ProcessStartInfo si = new ProcessStartInfo();
si.UseShellExecute = false;
si.RedirectStandardOutput = si.RedirectStandardError = true;
si.WorkingDirectory = JNetReflectorHelperTempFolder;
si.CreateNoWindow = true;
si.UseShellExecute = false;
si.FileName = Path.Combine(javapFullPath != null ? javapFullPath : string.Empty, "javap");
si.Arguments = arguments;
process = Process.Start(si);
TimeSpan initial = process.TotalProcessorTime;
int cycles = 0;
while ((exited = process.WaitForExit(100)) == false)
{
process.Refresh();
TimeSpan current = process.TotalProcessorTime;
if ((current - initial) < TimeSpan.FromMilliseconds(10)) break; // process is idle???
if (++cycles > toBeAnalyzed.Count) break; // elapsed max cycles
}
if (exited && process.ExitCode != 0) throw new InvalidOperationException($"javap falied with error {process.ExitCode}");
Dictionary<string, string> map = new Dictionary<string, string>();
string line;
int classCounter = -1;
string methodName = string.Empty;
string className = string.Empty;
bool nextLineIsDescriptor = false;
while ((line = process.StandardOutput.ReadLine()) != null)
{
if (line.Contains("Compiled from"))
{
if (classCounter != -1) { dict.TryAdd(toBeAnalyzed[classCounter], map); }
classCounter++;
className = toBeAnalyzed[classCounter].Name;
map = new Dictionary<string, string>();
}
if (nextLineIsDescriptor)
{
nextLineIsDescriptor = false;
string signature = line.TrimStart().TrimEnd();
signature = signature.Remove(0, "descriptor: ".Length);
map.Add(methodName, signature);
}
bool isInterfaceOrClassLine = line.Contains("class") || line.Contains("interface");
if (line.Contains("public") && !isInterfaceOrClassLine)
{
nextLineIsDescriptor = true;
methodName = line.TrimStart().TrimEnd();
methodName = methodName.RemoveThrowsAndCleanupSignature();
methodName = methodName.AddClassNameToSignature(className);
}
}
dict.TryAdd(toBeAnalyzed[classCounter], map);
}
catch { }
finally
{
if (!exited && !process.HasExited) try { process?.Kill(); } catch { }
}
}
return dict;
}
public static IReadOnlyDictionary<string, string> ExtractJavaInfo(Class clazz, string classPath, string javapFullPath = null)
{
IReadOnlyDictionary<string, string> result = null;
Process process = null;
bool exited = false;
try
{
string className = clazz.Name;
ProcessStartInfo si = new ProcessStartInfo();
si.UseShellExecute = false;
si.RedirectStandardOutput = si.RedirectStandardError = true;
si.WorkingDirectory = JNetReflectorHelperTempFolder;
si.CreateNoWindow = true;
si.UseShellExecute = false;
si.FileName = Path.Combine(javapFullPath != null ? javapFullPath : string.Empty, "javap");
si.Arguments = (string.IsNullOrWhiteSpace(classPath) ? string.Empty : $"-cp {classPath} ") + "-s " + className.Replace('$', '.');
process = Process.Start(si);
exited = process.WaitForExit(10000);
if (exited && process.ExitCode != 0) return result;
Dictionary<string, string> map = new Dictionary<string, string>();
string line;
int lineCounter = 0;
string methodName = string.Empty;
bool nextLineIsDescriptor = false;
while ((line = process.StandardOutput.ReadLine()) != null)
{
lineCounter++;
if (lineCounter < 3) continue;
if (nextLineIsDescriptor)
{
nextLineIsDescriptor = false;
string signature = line.TrimStart().TrimEnd();
signature = signature.Remove(0, "descriptor: ".Length);
map.Add(methodName, signature);
}
bool isInterfaceOrClassLine = line.Contains("class") || line.Contains("interface");
if (line.Contains("public") && !isInterfaceOrClassLine)
{
nextLineIsDescriptor = true;
methodName = line.TrimStart().TrimEnd();
methodName = methodName.RemoveThrowsAndCleanupSignature();
methodName = methodName.AddClassNameToSignature(className);
}
}
result = map;
}
catch { }
finally
{
if (!exited && !process.HasExited) try { process?.Kill(); } catch { }
}
return result;
}
/// <summary>
/// Find all <see cref="Class"/>es in the classpath
/// </summary>
/// <returns><see cref="Collection{E}"/> of <see cref="Class"/></returns>
public static Collection<Class> Find() => SExecute<Collection<Class>>("find");
/// <summary>
/// Find all <see cref="Class"/>es with <paramref name="packageOrModuleName"/>
/// </summary>
/// <param name="packageOrModuleName">Pattern to search</param>
/// <param name="isModule"><see langword="true"/> for modules, otherwise <see langword="false"/></param>
/// <returns><see cref="Collection{E}"/> of <see cref="Class"/></returns>
public static Collection<Class> Find(string packageOrModuleName, bool isModule) => SExecute<Collection<Class>>("find", packageOrModuleName, isModule);
}
}