summaryrefslogtreecommitdiff
path: root/Tools/Java/Source/MigrationTools/org/tianocore/migration/SourceFileReplacer.java
blob: 6bf0b24b53b4701c58813ae103fefba9e7fef99f (plain)
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/** @file
 
 Copyright (c) 2006, Intel Corporation
 All rights reserved. This program and the accompanying materials
 are licensed and made available under the terms and conditions of the BSD License
 which accompanies this distribution.  The full text of the license may be found at
 http://opensource.org/licenses/bsd-license.php
 
 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
 
 **/
package org.tianocore.migration;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.tianocore.UsageTypes;

public final class SourceFileReplacer implements Common.ForDoAll {
	private static final SourceFileReplacer SFReplacer = new SourceFileReplacer();

	private ModuleInfo mi;

	private static final Set<Common.Laplace> Laplaces = new HashSet<Common.Laplace>();

	// these sets are used only for printing log of the changes in current file
	private static final Set<r8tor9> filefunc = new HashSet<r8tor9>();

	private static final Set<r8tor9> filemacro = new HashSet<r8tor9>();

	private static final Set<r8tor9> fileguid = new HashSet<r8tor9>();

	private static final Set<r8tor9> fileppi = new HashSet<r8tor9>();

	private static final Set<r8tor9> fileprotocol = new HashSet<r8tor9>();

	private static final Set<String> filer8only = new HashSet<String>();

	private static final String[] specialhoblibfunc = { "BuildModuleHob",
			"BuildResourceDescriptorHob", "BuildFvHob", "BuildCpuHob",
			"BuildGuidDataHob", "BuildStackHob", "BuildBspStoreHob",
			"BuildMemoryAllocationHob" };

	private static final String[] peiserviceslibfunc = { "InstallPpi",
			"ReInstallPpi", "LocatePpi", "NotifyPpi", "GetBootMode",
			"SetBootMode", "GetHobList", "CreateHob", "FfsFindNextVolume",
			"FfsFindNextFile", "FfsFindSectionData", "InstallPeiMemory",
			"AllocatePages", "AllocatePool", "PeiResetSystem" };

	// ---------------------------------------inner
	// classes---------------------------------------//
	private static class r8tor9 {
		r8tor9(String r8, String r9) {
			r8thing = r8;
			r9thing = r9;
		}

		public String r8thing;

		public String r9thing;
	}

	private class IdleLaplace extends Common.Laplace {
		public String operation(String wholeline) {
			return replaceLibrary(wholeline, mi.hashmacro);
		}

		public boolean recognize(String filename) {
			return filename.contains(".h") || filename.contains(".H")
					|| filename.contains(".uni") || filename.contains(".s")
					|| filename.contains(".S") || filename.contains(".asm")
					|| (!filename.contains(".inf") && filename.contains(".i"));
		}

		public String namechange(String oldname) {
			if (oldname.contains(".H")) {
				return oldname.replaceFirst(".H", ".h");
			} else {
				return oldname;
			}
		}
	}

	private class DxsLaplace extends Common.Laplace {
		public String operation(String wholeline) {
			wholeline = replaceMacro(wholeline, mi.hashnonlocalmacro);
			if (mi.getModuleType().equals("PEIM")) {
				return addincludefile(wholeline, "\\<PeimDepex.h\\>");
			} else {
				return addincludefile(wholeline, "\\<DxeDepex.h\\>");
			}
		}

		public boolean recognize(String filename) {
			return filename.contains(".dxs");
		}

		public String namechange(String oldname) {
			return oldname;
		}
	}

	private class CLaplace extends Common.Laplace {
		public String operation(String wholeline) {
			// remove EFI_DRIVER_ENTRY_POINT
			wholeline = wholeline.replaceAll(
					"(EFI_[A-Z]+_ENTRY_POINT\\s*\\(\\s*\\w(\\w|\\d)*\\s*\\))",
					MigrationTool.MIGRATIONCOMMENT + " $1");
			// redefine module entry point for some self-relocated modules
			wholeline = wholeline.replaceAll(mi.entrypoint + "([^{]*?})",
					"_ModuleEntryPoint" + "$1");
			// remove R8 library contractor
			wholeline = wholeline.replaceAll(
					"(\\b(?:Efi|Dxe)InitializeDriverLib\\b)",
					MigrationTool.MIGRATIONCOMMENT + " $1");
			// Add Library Class for potential reference of gBS, gRT & gDS.
			if (Common.find(wholeline, "\\bg?BS\\b")) {
				mi.hashrequiredr9libs.add("UefiBootServicesTableLib");
			}
			if (Common.find(wholeline, "\\bg?RT\\b")) {
				mi.hashrequiredr9libs.add("UefiRuntimeServicesTableLib");
			}
			if (Common.find(wholeline, "\\bgDS\\b")) {
				mi.hashrequiredr9libs.add("DxeServicesTableLib");
			}

			wholeline = replaceLibrary(wholeline, mi.hashnonlocalfunc);
			wholeline = replaceLibrary(wholeline, mi.hashmacro);
			// Converting macro
			wholeline = replaceMacro(wholeline, mi.hashnonlocalmacro);

			// Converting guid
			replaceGuid(wholeline, mi.guids, "guid", fileguid);
			replaceGuid(wholeline, mi.ppis, "ppi", fileppi);
			replaceGuid(wholeline, mi.protocols, "protocol", fileprotocol);

			// Converting Pei
			if (mi.getModuleType().matches("PEIM")) {
				//
				// Try to remove PeiServicesTablePointer;
				// 
				wholeline = dropPeiServicesPointer(wholeline);
				//
				// Drop the possible return Status of Hob building function.
				// 
				wholeline = drophobLibReturnStatus(wholeline);
			}
			//
			// Expand obsolete R8 macro.
			// 
			wholeline = replaceObsoleteMacro(wholeline);

			show(filefunc, "function");
			show(filemacro, "macro");
			show(fileguid, "guid");
			show(fileppi, "ppi");
			show(fileprotocol, "protocol");
			if (!filer8only.isEmpty()) {
				MigrationTool.ui.println("Converting r8only : " + filer8only);
			}

			filefunc.clear();
			filemacro.clear();
			fileguid.clear();
			fileppi.clear();
			fileprotocol.clear();
			filer8only.clear();

			return wholeline;
		}

		public boolean recognize(String filename) {
			return filename.contains(".c") || filename.contains(".C");
		}

		public String namechange(String oldname) {
			if (oldname.contains(".C")) {
				return oldname.replaceFirst(".C", ".c");
			} else {
				return oldname;
			}
		}
	}

	// ---------------------------------------inner
	// classes---------------------------------------//

	// -------------------------------------process
	// functions-------------------------------------//
	private static final String addincludefile(String wholeline, String hfile) {
		return wholeline.replaceFirst("(\\*/\\s)", "$1\n#include " + hfile
				+ "\n");
	}

	private static final void show(Set<r8tor9> hash, String sh) {
		Iterator<r8tor9> it = hash.iterator();
		r8tor9 temp;
		if (!hash.isEmpty()) {
			MigrationTool.ui.print("Converting " + sh + " : ");
			while (it.hasNext()) {
				temp = it.next();
				MigrationTool.ui.print("[" + temp.r8thing + "->" + temp.r9thing
						+ "] ");
			}
			MigrationTool.ui.println("");
		}
	}

	private static final void replaceGuid(String line, Set<String> hash,
			String kind, Set<r8tor9> filehash) {
		Iterator<String> it;
		String r8thing;
		String r9thing;
		it = hash.iterator();
		while (it.hasNext()) {
			r8thing = it.next();
			if ((r9thing = MigrationTool.db.getR9Guidname(r8thing)) != null) {
				if (!r8thing.equals(r9thing)) {
					if (line.contains(r8thing)) {
						line = line.replaceAll(r8thing, r9thing);
						filehash.add(new r8tor9(r8thing, r9thing));
					}
				}
			}
		}
	}

	private final String dropPeiServicesPointer(String wholeline) {
		String peiServicesTablePointer;
		String peiServicesTableCaller;
		String regPeiServices;
		Pattern ptnPei;
		Matcher mtrPei;

		peiServicesTablePointer = "\\w(?:\\w|[0-9]|->)*";
		peiServicesTableCaller = "\\(\\*\\*?\\s*(" + peiServicesTablePointer
				+ ")\\s*\\)[.-]>?\\s*";
		for (int i = 0; i < peiserviceslibfunc.length; i++) {
			regPeiServices = peiServicesTableCaller + peiserviceslibfunc[i]
					+ "\\s*\\(\\s*\\1\\s*,(\\t| )*";
			ptnPei = Pattern.compile(regPeiServices);
			mtrPei = ptnPei.matcher(wholeline);
			if (mtrPei.find()) {
				wholeline = mtrPei.replaceAll("PeiServices"
						+ peiserviceslibfunc[i] + " (");
				mi.hashrequiredr9libs.add("PeiServicesLib");
			}
		}
		regPeiServices = peiServicesTableCaller + "(CopyMem|SetMem)"
				+ "\\s*\\((\\t| )*";
		ptnPei = Pattern.compile(regPeiServices);
		mtrPei = ptnPei.matcher(wholeline);
		if (mtrPei.find()) {
			wholeline = mtrPei.replaceAll("$2 (");
			mi.hashrequiredr9libs.add("BaseMemoryLib");
		}

		ptnPei = Pattern.compile("#%+(\\s*\\(+\\s*)" + peiServicesTablePointer
				+ "\\s*,\\s*", Pattern.MULTILINE);
		mtrPei = ptnPei.matcher(wholeline);
		while (mtrPei.find()) {
			wholeline = mtrPei.replaceAll("$1");
		}

		return wholeline;
	}

	private final String drophobLibReturnStatus(String wholeline) { // or use
																	// regex to
																	// find
																	// pattern
																	// "Status =
																	// ..."
		Pattern ptnhobstatus;
		Matcher mtrhobstatus;
		String templine = wholeline;
		for (int i = 0; i < specialhoblibfunc.length; i++) {
			do {
				ptnhobstatus = Pattern.compile(
						"((?:\t| )*)(\\w(?:\\w|\\d)*)\\s*=\\s*"
								+ specialhoblibfunc[i] + "(.*?;)",
						Pattern.DOTALL);
				mtrhobstatus = ptnhobstatus.matcher(templine);
				if (!mtrhobstatus.find()) {
					break;
				}
				String captureIndent = mtrhobstatus.group(1);
				String captureStatus = mtrhobstatus.group(2);
				String replaceString = captureIndent + specialhoblibfunc[i]
						+ mtrhobstatus.group(3) + "\n";
				replaceString += captureIndent
						+ MigrationTool.MIGRATIONCOMMENT
						+ "R9 Hob-building library functions will assert if build failure.\n";
				replaceString += captureIndent + captureStatus
						+ " = EFI_SUCCESS;";
				templine = mtrhobstatus.replaceFirst(replaceString);
			} while (true);
		}
		return templine;
	}

	private final String replaceMacro(String wholeline, Set<String> symbolSet) {
		String r8thing;
		String r9thing;
		Iterator<String> it;

		it = symbolSet.iterator();
		while (it.hasNext()) { // macros are all assumed MdePkg currently
			r8thing = it.next();
			// mi.hashrequiredr9libs.add(MigrationTool.db.getR9Lib(r8thing));
			if ((r9thing = MigrationTool.db.getR9Macro(r8thing)) != null) {
				if (wholeline.contains(r8thing)) {
					String findString = "(?<!(?:\\d|\\w))" + r8thing
							+ "(?!(?:\\d|\\w))";
					wholeline = wholeline.replaceAll(findString, r9thing);
					filemacro.add(new r8tor9(r8thing, r9thing));
				}
			}
		}
		return wholeline;
	}

	private final String replaceLibrary(String wholeline, Set<String> symbolSet) {
		boolean addr8 = false;
		// start replacing names
		String r8thing;
		String r9thing;
		Iterator<String> it;
		// Converting non-locla function
		it = symbolSet.iterator();
		while (it.hasNext()) {
			r8thing = it.next();
			mi.addLibraryClass(MigrationTool.db.getR9Lib(r8thing),
					UsageTypes.ALWAYS_CONSUMED);
			// mi.hashrequiredr9libs.add(MigrationTool.db.getR9Lib(r8thing)); //
			// add a library here

			r8tor9 temp;
			if ((r9thing = MigrationTool.db.getR9Func(r8thing)) != null) {
				if (!r8thing.equals(r9thing)) {
					if (wholeline.contains(r8thing)) {
						String findString = "(?<!(?:\\d|\\w))" + r8thing
								+ "(?!(?:\\d|\\w))";
						wholeline = wholeline.replaceAll(findString, r9thing);
						filefunc.add(new r8tor9(r8thing, r9thing));
						Iterator<r8tor9> rt = filefunc.iterator();
						while (rt.hasNext()) {
							temp = rt.next();
							if (MigrationTool.db.r8only.contains(temp.r8thing)) {
								filer8only.add(r8thing);
								mi.hashr8only.add(r8thing);
								addr8 = true;
							}
						}
					}
				}
			}
		} // is any of the guids changed?
		if (addr8 == true) {
			wholeline = addincludefile(wholeline, "\"R8Lib.h\"");
		}
		return wholeline;
	}

	private final String replaceObsoleteMacro(String wholeline) {
		Matcher mtrmac;
		mtrmac = Pattern.compile("EFI_IDIV_ROUND\\((.*), (.*)\\)").matcher(
				wholeline);
		if (mtrmac.find()) {
			wholeline = mtrmac
					.replaceAll("\\($1 \\/ $2 \\+ \\(\\(\\(2 \\* \\($1 \\% $2\\)\\) \\< $2\\) \\? 0 \\: 1\\)\\)");
		}
		mtrmac = Pattern.compile("EFI_MIN\\((.*), (.*)\\)").matcher(wholeline);
		if (mtrmac.find()) {
			wholeline = mtrmac
					.replaceAll("\\(\\($1 \\< $2\\) \\? $1 \\: $2\\)");
		}
		mtrmac = Pattern.compile("EFI_MAX\\((.*), (.*)\\)").matcher(wholeline);
		if (mtrmac.find()) {
			wholeline = mtrmac
					.replaceAll("\\(\\($1 \\> $2\\) \\? $1 \\: $2\\)");
		}
		mtrmac = Pattern.compile("EFI_UINTN_ALIGNED\\((.*)\\)").matcher(
				wholeline);
		if (mtrmac.find()) {
			wholeline = mtrmac
					.replaceAll("\\(\\(\\(UINTN\\) $1\\) \\& \\(sizeof \\(UINTN\\) \\- 1\\)\\)");
		}
		if (wholeline.contains("EFI_UINTN_ALIGN_MASK")) {
			wholeline = wholeline.replaceAll("EFI_UINTN_ALIGN_MASK",
					"(sizeof (UINTN) - 1)");
		}
		return wholeline;
	}

	private final void addr8only() throws Exception {
		String paragraph = null;
		String line = Common.file2string(MigrationTool.db.DatabasePath
				+ File.separator + "R8Lib.c");
		PrintWriter outfile1 = new PrintWriter(new BufferedWriter(
				new FileWriter(MigrationTool.ModuleInfoMap.get(mi)
						+ File.separator + "Migration_" + mi.modulename
						+ File.separator + "R8Lib.c")));
		PrintWriter outfile2 = new PrintWriter(new BufferedWriter(
				new FileWriter(MigrationTool.ModuleInfoMap.get(mi)
						+ File.separator + "Migration_" + mi.modulename
						+ File.separator + "R8Lib.h")));
		Pattern ptnr8only = Pattern.compile(
				"////#?(\\w*)?(.*?R8_(\\w*).*?)////~", Pattern.DOTALL);
		Matcher mtrr8only = ptnr8only.matcher(line);
		Matcher mtrr8onlyhead;

		// add head comment
        if (mi.license != null) {
            String header = "/**@file\n  Copyright (c) 2007, Intel Corporation\n\n" + 
            mi.license.replace("      ", "  ") + "**/\n\n";		
            outfile1.append(header);
    		outfile2.append(header);
        }
        
    // add functions body
		while (mtrr8only.find()) {
			if (mi.hashr8only.contains(mtrr8only.group(3))) {
				paragraph = mtrr8only.group(2);
				outfile1.append(paragraph + "\n\n");
				if (mtrr8only.group(1).length() != 0) {
					mi.hashrequiredr9libs.add(mtrr8only.group(1));
				}
				// generate R8lib.h
				while ((mtrr8onlyhead = Func.ptnbrace.matcher(paragraph))
						.find()) {
					paragraph = mtrr8onlyhead.replaceAll(";");
				}
				outfile2.append(paragraph + "\n\n");
			}
		}
		outfile1.flush();
		outfile1.close();
		outfile2.flush();
		outfile2.close();

		mi.localmodulesources.add("R8Lib.h");
		mi.localmodulesources.add("R8Lib.c");
	}

	// -------------------------------------process
	// functions-------------------------------------//

	// -----------------------------------ForDoAll-----------------------------------//
	public void run(String filepath) throws Exception {
		String inname = filepath.replace(mi.temppath + File.separator, "");
		String tempinpath = mi.temppath + File.separator;
		String tempoutpath = MigrationTool.ModuleInfoMap.get(mi)
				+ File.separator + "Migration_" + mi.modulename
				+ File.separator;

		Iterator<Common.Laplace> itLaplace = Laplaces.iterator();
		while (itLaplace.hasNext()) {
			Common.Laplace lap = itLaplace.next();
			if (lap.recognize(inname)) {
				MigrationTool.ui.println("\nHandling file: " + inname);
				lap.transform(tempinpath + inname, tempoutpath
						+ lap.namechange(inname));
			}
		}
	}

	public boolean filter(File dir) {
		return true;
	}

	// -----------------------------------ForDoAll-----------------------------------//

	private final void setModuleInfo(ModuleInfo moduleinfo) {
		mi = moduleinfo;
	}

	private final void start() throws Exception {
		Laplaces.add(new DxsLaplace());
		Laplaces.add(new CLaplace());
		Laplaces.add(new IdleLaplace());

		Common.toDoAll(mi.temppath, this, Common.FILE);

		if (!mi.hashr8only.isEmpty()) {
			addr8only();
		}

		Laplaces.clear();
	}

	public static final void fireAt(ModuleInfo moduleinfo) throws Exception {
		SFReplacer.setModuleInfo(moduleinfo);
		SFReplacer.start();
	}
}