file_name stringlengths 6 86 | file_path stringlengths 45 249 | content stringlengths 47 6.26M | file_size int64 47 6.26M | language stringclasses 1 value | extension stringclasses 1 value | repo_name stringclasses 767 values | repo_stars int64 8 14.4k | repo_forks int64 0 1.17k | repo_open_issues int64 0 788 | repo_created_at stringclasses 767 values | repo_pushed_at stringclasses 767 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
DataBranchGoto.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBranchGoto.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.IOException;
/**
* DataBranchGoto
*
*
* @author Robert Field
*/
public class DataBranchGoto extends DataBranch {
public DataBranchGoto(int rootId, int bciFromStart, int bciFromEnd) {
super(rootId, bciFromStart, bciFromEnd);
}
DataBlockTarget branchTarget() {
return getBranchTargets().get(0);
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.GOTO;
}
DataBranchGoto(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 1,824 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockTargetCond.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlockTargetCond.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
*
* @author Robert
*/
public class DataBlockTargetCond extends DataBlockTarget {
private final boolean side;
public DataBlockTargetCond(int rootId, boolean side) {
super(rootId);
this.side = side;
}
public DataBlockTargetCond(int rootId, boolean side, int slot, boolean attached, long count) {
super(rootId, slot, attached, count);
this.side = side;
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (this.side ? 1 : 0);
return hash;
}
public boolean equals(Object o) {
return super.equals(o) && side == ((DataBlockTargetCond) o).side;
}
public boolean side() {
return side;
}
/**
* Does the previous block fall into this one?
*/
public boolean isFallenInto() {
return !side;
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.COND;
}
void xmlAttrsValue(XmlContext cxt) {
cxt.attr(XmlNames.VALUE, side);
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.writeBoolean(side);
}
DataBlockTargetCond(int rootId, DataInput in) throws IOException {
super(rootId, in);
side = in.readBoolean();
}
} | 2,651 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
InstrumentationParams.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/InstrumentationParams.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.instrument.InstrumentationOptions.ABSTRACTMODE;
import com.sun.tdk.jcov.instrument.InstrumentationOptions.InstrumentationMode;
import com.sun.tdk.jcov.instrument.InstrumentationPlugin;
import com.sun.tdk.jcov.runtime.Collect;
import com.sun.tdk.jcov.runtime.CollectDetect;
import com.sun.tdk.jcov.util.Utils;
import com.sun.tdk.jcov.util.Utils.Pattern;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import java.util.TreeSet;
/**
*
* @author Andrey Titov
*/
public class InstrumentationParams {
private boolean detectInternal;
private boolean dynamicCollect;
private boolean classesReload;
private boolean instrumentNative;
private boolean instrumentSynthetic;
private boolean instrumentAnonymous;
private InstrumentationOptions.ABSTRACTMODE instrumentAbstract;
private boolean instrumentFields;
private String callerInclude;
private String callerExclude;
private String[] includes;
private String[] excludes;
private String[] callerIncludes;
private String[] callerExcludes;
private String[] inner_includes;
private String[] inner_excludes;
private InstrumentationOptions.InstrumentationMode mode;
private String saveBegin;
private String saveEnd;
private String[] savesBegin;
private String[] savesEnd;
private Pattern[] alls;
private Pattern[] all_modules;
private Pattern[] inner_alls;
private boolean innerInvocations;
private InstrumentationPlugin plugin;
//TODO replace by a builder!!!
public InstrumentationParams(boolean dynamicCollect, boolean instrumentNative, boolean instrumentFields,
boolean detectInternal, ABSTRACTMODE instrumentAbstract, String[] includes,
String[] excludes, String[] callerIncludes, String[] callerExcludes,
InstrumentationMode mode) {
this(dynamicCollect, instrumentNative, instrumentFields, detectInternal, instrumentAbstract,
includes, excludes, callerIncludes, callerExcludes, mode, null, null);
}
public InstrumentationParams(boolean instrumentNative, boolean instrumentFields, boolean instrumentAbstract,
String[] includes, String[] excludes, InstrumentationMode mode) {
this(false, instrumentNative, instrumentFields, false,
instrumentAbstract ? ABSTRACTMODE.DIRECT : ABSTRACTMODE.NONE, includes, excludes,
null, null, mode, null, null);
}
public InstrumentationParams(boolean instrumentNative, boolean instrumentFields, boolean instrumentAbstract,
String[] includes, String[] excludes, String[] m_includes, String[] m_excludes,
InstrumentationMode mode) {
this(false, false, false, instrumentNative, instrumentFields,
false, instrumentAbstract ? ABSTRACTMODE.DIRECT : ABSTRACTMODE.NONE, includes, excludes,
null, null, m_includes, m_excludes, mode, null, null);
}
public InstrumentationParams(boolean instrumentNative, boolean instrumentFields, boolean instrumentAbstract,
String[] includes, String[] excludes, InstrumentationMode mode,
String[] saveBegin, String[] saveEnd) {
this(false, instrumentNative, instrumentFields, false,
instrumentAbstract ? ABSTRACTMODE.DIRECT : ABSTRACTMODE.NONE, includes, excludes,
null, null, mode, saveBegin, saveEnd);
}
public InstrumentationParams(boolean instrumentNative, boolean instrumentFields, boolean instrumentAbstract,
String[] includes, String[] excludes,
String[] callerincludes, String[] callersexcludes,
InstrumentationMode mode, String[] saveBegin, String[] saveEnd) {
this(false, instrumentNative, instrumentFields, false,
instrumentAbstract ? ABSTRACTMODE.DIRECT : ABSTRACTMODE.NONE,
includes, excludes, callerincludes, callersexcludes, mode, saveBegin, saveEnd);
}
public InstrumentationParams(boolean dynamicCollect, boolean instrumentNative, boolean instrumentFields,
boolean detectInternal, ABSTRACTMODE instrumentAbstract,
String[] includes, String[] excludes, String[] callerIncludes, String[] callerExcludes,
InstrumentationMode mode, String[] saveBegin, String[] saveEnd) {
this(false, dynamicCollect, instrumentNative, instrumentFields, detectInternal, instrumentAbstract,
includes, excludes, callerIncludes, callerExcludes, mode, saveBegin, saveEnd);
}
public InstrumentationParams(boolean classesReload, boolean dynamicCollect, boolean instrumentNative,
boolean instrumentFields, boolean detectInternal, ABSTRACTMODE instrumentAbstract,
String[] includes, String[] excludes, String[] callerIncludes, String[] callerExcludes,
InstrumentationMode mode, String[] saveBegin, String[] saveEnd) {
this(true, classesReload, dynamicCollect, instrumentNative, instrumentFields, detectInternal,
instrumentAbstract, includes, excludes, callerIncludes, callerExcludes, mode, saveBegin, saveEnd);
}
public InstrumentationParams(boolean innerInvocations, boolean classesReload, boolean dynamicCollect,
boolean instrumentNative, boolean instrumentFields, boolean detectInternal,
ABSTRACTMODE instrumentAbstract,
String[] includes, String[] excludes, String[] callerIncludes, String[] callerExcludes,
InstrumentationMode mode, String[] saveBegin, String[] saveEnd) {
this(innerInvocations, classesReload, dynamicCollect, instrumentNative, instrumentFields, detectInternal,
instrumentAbstract, includes, excludes, callerIncludes, callerExcludes,
null, null, mode, saveBegin, saveEnd);
}
public InstrumentationParams(boolean innerInvocations, boolean classesReload, boolean dynamicCollect,
boolean instrumentNative, boolean instrumentFields, boolean detectInternal,
ABSTRACTMODE instrumentAbstract,
String[] includes, String[] excludes, String[] callerIncludes, String[] callerExcludes,
String[] m_includes, String[] m_excludes, InstrumentationMode mode,
String[] saveBegin, String[] saveEnd) {
this(innerInvocations, classesReload, dynamicCollect, instrumentNative, instrumentFields, detectInternal,
instrumentAbstract, includes, excludes, callerIncludes, callerExcludes,
null, null, mode, saveBegin, saveEnd, null);
}
public InstrumentationParams(boolean innerInvocations, boolean classesReload, boolean dynamicCollect,
boolean instrumentNative, boolean instrumentFields, boolean detectInternal,
ABSTRACTMODE instrumentAbstract,
String[] includes, String[] excludes, String[] callerIncludes, String[] callerExcludes,
String[] m_includes, String[] m_excludes, InstrumentationMode mode,
String[] saveBegin, String[] saveEnd, InstrumentationPlugin plugin) {
this.innerInvocations = innerInvocations;
this.detectInternal = detectInternal;
this.dynamicCollect = dynamicCollect;
this.classesReload = classesReload;
this.instrumentNative = instrumentNative;
this.instrumentAbstract = instrumentAbstract;
this.instrumentFields = instrumentFields;
if (includes == null) {
includes = new String[]{""};
}
if (excludes == null) {
excludes = new String[]{""};
}
if (m_includes == null) {
m_includes = new String[]{""};
}
if (m_excludes == null) {
m_excludes = new String[]{""};
}
this.includes = includes;
this.excludes = excludes;
if (callerIncludes == null) {
callerIncludes = new String[0];
}
if (callerExcludes == null) {
callerExcludes = new String[0];
}
this.callerIncludes = callerIncludes;
this.callerExcludes = callerExcludes;
this.savesBegin = saveBegin;
this.savesEnd = saveEnd;
this.mode = mode;
// nulls will be changed to "" in concatRegexps
this.saveBegin = InstrumentationOptions.concatRegexps(saveBegin);
this.saveEnd = InstrumentationOptions.concatRegexps(saveEnd);
this.callerInclude = InstrumentationOptions.concatRegexps(callerIncludes);
this.callerExclude = InstrumentationOptions.concatRegexps(callerExcludes);
this.alls = Utils.concatFilters(includes, excludes);
this.all_modules = Utils.concatModuleFilters(m_includes, m_excludes);
this.inner_alls = Utils.concatFilters(inner_includes, inner_excludes);
this.plugin = plugin;
}
public boolean isDetectInternal() {
return detectInternal;
}
public boolean isDynamicCollect() {
return dynamicCollect;
}
public boolean isClassesReload() {
return classesReload;
}
public boolean isInstrumentNative() {
return instrumentNative;
}
public boolean isInstrumentFields() {
return instrumentFields;
}
public boolean isInstrumentSynthetic() {
return instrumentSynthetic;
}
public boolean isInstrumentAnonymous() {
return instrumentAnonymous;
}
public InstrumentationPlugin getInstrumentationPlugin() { return plugin; }
// public boolean skipNotCoveredClasses() {
// return dynamicCollect;
// }
//
public boolean isInstrumentAbstract() {
return instrumentAbstract != InstrumentationOptions.ABSTRACTMODE.NONE;
}
public void enable() {
Collect.enableCounts();
if (instrumentFields || instrumentAbstract != InstrumentationOptions.ABSTRACTMODE.NONE) {
CollectDetect.enableInvokeCounts();
}
if (detectInternal) {
CollectDetect.enableDetectInternal();
}
Collect.enabled = true;
}
public boolean isIncluded(String classname) {
return Utils.accept(alls, null, "/" + classname, null);
}
public boolean isInnerInstrumentationIncludes(String classname) {
return Utils.accept(inner_alls, null, "/" + classname, null);
}
public boolean isModuleIncluded(String modulename) {
return Utils.accept(all_modules, null, modulename, null);
}
public boolean isCallerFilterOn() {
return /*dynamicCollect &&*/ !(callerInclude.equals(".*") && callerExclude.equals(""));
}
public boolean isInnerInvacationsOff() {
return !innerInvocations;
}
public boolean isCallerFilterAccept(String className) {
boolean name = className.matches(callerInclude) && !className.matches(callerExclude);
return name;
}
public boolean isStackMapShouldBeUpdated() {
return mode.equals(InstrumentationMode.BRANCH);
}
public InstrumentationMode getMode() {
return mode;
}
public boolean isDataSaveFilterAccept(String className, String methodName, boolean isBegin) {
return (className + "." + methodName).matches(isBegin ? saveBegin : saveEnd);
}
public boolean isDataSaveSpecified() {
return saveBegin != null || saveEnd != null;
}
public static InstrumentationParams mergeParams(InstrumentationParams first, InstrumentationParams other) {
boolean detectInternal = first.detectInternal || other.detectInternal;
String[] includes = mergeFilter(first.includes, other.includes, true);
String[] excludes = mergeFilter(first.excludes, other.excludes, false);
String[] callerIncludes = mergeFilter(first.callerIncludes, other.callerIncludes, true);
String[] callerExcludes = mergeFilter(first.callerExcludes, other.callerExcludes, false);
boolean dynamicCollected = first.dynamicCollect | other.dynamicCollect;
return new InstrumentationParams(dynamicCollected, first.instrumentNative, first.instrumentFields, detectInternal, first.instrumentAbstract, includes, excludes, callerIncludes, callerExcludes, first.mode);
}
public static InstrumentationParams mergeDetectInternalOnly(InstrumentationParams first, InstrumentationParams other) {
boolean detectInternal = first.detectInternal || other.detectInternal;
return new InstrumentationParams(first.dynamicCollect, first.instrumentNative, first.instrumentFields, detectInternal, first.instrumentAbstract, first.includes, first.excludes, first.callerIncludes, first.callerExcludes, first.mode);
}
//moveto utils
public static String[] mergeFilter(String[] filter1, String[] filter2, boolean union) {
Set<String> res = new TreeSet<String>();
if (union) {
res.addAll(Arrays.asList(filter1));
res.addAll(Arrays.asList(filter2));
return res.toArray(new String[res.size()]);
} else {//intersection
for (String e1 : filter1) {
for (String e2 : filter2) {
if (e1.equals(e2)) {
res.add(e2);
}
}
}
}
return res.toArray(new String[res.size()]);
}
public String[] getIncludes() {
return includes;
}
public String[] getExcludes() {
return excludes;
}
public String[] getCallerIncludes() {
return callerIncludes;
}
public String[] getCallerExcludes() {
return callerExcludes;
}
public static InstrumentationParams setMode(InstrumentationParams params, InstrumentationMode mode) {
return new InstrumentationParams(params.dynamicCollect, params.instrumentNative, params.instrumentFields, params.detectInternal, params.instrumentAbstract, params.includes, params.excludes, params.callerIncludes, params.callerExcludes, mode, params.savesBegin, params.savesEnd);
}
public void setExcludes(String[] excludes) {
this.excludes = excludes;
this.alls = Utils.concatFilters(includes, excludes);
}
public void setIncludes(String[] includes) {
this.includes = includes;
this.alls = Utils.concatFilters(includes, excludes);
}
public InstrumentationParams setInnerExcludes(String[] excludes) {
this.inner_excludes = excludes;
this.inner_alls = Utils.concatFilters(inner_includes, excludes);
return this;
}
public InstrumentationParams setInnerIncludes(String[] includes) {
this.inner_includes = includes;
this.inner_alls = Utils.concatFilters(includes, inner_excludes);
return this;
}
public InstrumentationParams setInstrumentSynthetic(boolean synth) {
instrumentSynthetic = synth;
return this;
}
public InstrumentationParams setInstrumentAnonymous(boolean anonym) {
instrumentAnonymous = anonym;
return this;
}
public InstrumentationParams setInnerInvocations(boolean inner) {
innerInvocations = inner;
return this;
}
public InstrumentationParams setInstrumentationPlugin(InstrumentationPlugin plugin) {
this.plugin = plugin;
return this;
}
void writeObject(DataOutput out) throws IOException {
DataAbstract.writeStrings(out, excludes);
DataAbstract.writeStrings(out, includes);
DataAbstract.writeStrings(out, callerExcludes);
DataAbstract.writeStrings(out, callerIncludes);
DataAbstract.writeStrings(out, savesBegin);
DataAbstract.writeStrings(out, savesEnd);
out.writeBoolean(classesReload);
out.writeBoolean(detectInternal);
out.writeBoolean(dynamicCollect);
out.writeBoolean(instrumentFields);
out.writeBoolean(instrumentNative);
out.writeBoolean(innerInvocations);
out.write(instrumentAbstract.ordinal());
out.write(mode.ordinal());
}
InstrumentationParams(DataInput in) throws IOException {
excludes = DataAbstract.readStrings(in);
includes = DataAbstract.readStrings(in);
callerExcludes = DataAbstract.readStrings(in);
callerIncludes = DataAbstract.readStrings(in);
savesBegin = DataAbstract.readStrings(in);
savesEnd = DataAbstract.readStrings(in);
classesReload = in.readBoolean();
detectInternal = in.readBoolean();
dynamicCollect = in.readBoolean();
instrumentFields = in.readBoolean();
instrumentNative = in.readBoolean();
innerInvocations = in.readBoolean();
instrumentAbstract = ABSTRACTMODE.values()[in.readByte()];
mode = InstrumentationMode.values()[in.readByte()];
this.plugin = null;
}
}
| 18,755 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
BasicBlock.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/BasicBlock.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.tools.DelegateIterator;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Set;
/**
* BasicBlock
*
* Depends on LabelNode (via code currently in MethodNode) using Label.info to
* hold the mapping between Label and LabelNode.
*
* This class is used in DataMethodWithBlocks to store blocks&branches.
* DataMethodWithBlocks contains an array of BasicBlocks. Each BasicBlock
* contains a set of DataBlocks and DataExit (DataExitSimple for just exiting
* methods; abstract DataBranch for branches). So any method consists of some
* blocks (DataBlock) and some instructions moving (GOTO) for branching
*
* @author Robert Field
*/
public class BasicBlock extends LocationConcrete {
private DataBlock fallenInto = null;
private final Set<DataBlock> blocks;
public DataExit exit = null;
/**
* Creates a new instance of BasicBlock
*/
public BasicBlock(int rootId, int startBCI) {
super(rootId, startBCI);
blocks = Collections.newSetFromMap(new IdentityHashMap<>());
}
/**
* Creates a new instance of BasicBlock
*/
BasicBlock(int rootId, int startBCI, int endBCI) {
super(rootId, startBCI, endBCI);
blocks = Collections.newSetFromMap(new IdentityHashMap<>());
}
public BasicBlock(int rootId) {
this(rootId, -1);
}
public void add(DataBlock blk) {
blocks.add(blk);
if (blk.isFallenInto()) {
fallenInto = blk;
}
blk.setConcreteLocation(this);
}
boolean contains(DataBlock blk) {
return blocks.contains(blk);
}
public DataBlock fallenInto() {
return fallenInto;
}
public void setExit(DataExit exit) {
this.exit = exit;
}
public Collection<DataBlock> blocks() {
return blocks;
}
boolean wasHit() {
return fallenInto() == null ? false : fallenInto().wasHit();
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.BLOCK;
}
@Override
void xmlBody(XmlContext ctx) {
// xmlEntries(ctx);
xmlDetailBody(ctx);
}
void xmlDetailBody(XmlContext ctx) {
if (ctx.showNonNested && blocks != null) {//BRANCH only
for (DataBlock block : blocks) {
if (!block.isNested()) {
block.xmlGen(ctx);
}
}
}
if (exit != null) {
exit.xmlGen(ctx);
}
}
public void checkCompatibility(BasicBlock other) throws MergeException {
if (blocks.size() != other.blocks().size()) {
throw new MergeException("Block has other number of data blocks than "
+ "it's merging copy, expected " + blocks.size() + "; found " + other.blocks().size(),
"", MergeException.HIGH);
}
if (exit instanceof DataBranch) {
if (!(other.exit instanceof DataBranch)) {
throw new MergeException("Block exit has other type than it's"
+ " merging copy, expected DataBranchAbstract; found " + other.exit,
"", MergeException.HIGH);
}
DataBranch branch = (DataBranch) exit;
DataBranch obranch = (DataBranch) other.exit;
if (branch.branchTargets.size() != obranch.branchTargets.size()) {
throw new MergeException("Block has other number of data blocks (targets) than "
+ "it's merging copy, expected " + blocks.size() + "; found " + other.blocks().size(),
"", MergeException.HIGH);
}
}
}
public void merge(BasicBlock other) {
boolean dynamicCollected = DataRoot.getInstance(rootId).getParams().isDynamicCollect() || DataRoot.getInstance(other.rootId).getParams().isDynamicCollect();
mergeDataBlocks(blocks, other.blocks(), dynamicCollected);
if (exit instanceof DataBranch) {
DataBranch branch = (DataBranch) exit;
DataBranch obranch = (DataBranch) other.exit;
mergeDataBlocks(branch.branchTargets, obranch.branchTargets, dynamicCollected);
}
}
private static void mergeDataBlocks(Collection<? extends DataBlock> blocks,
Collection<? extends DataBlock> oblocks, boolean dynamicCollected) {
for (DataBlock b : blocks) {
for (DataBlock bo : oblocks) {
if (dynamicCollected) {
if (b.startBCI() == bo.startBCI()
&& b.endBCI() == bo.endBCI()
&& (b.getClass() == bo.getClass())
&& b.isFallenInto() == bo.isFallenInto()) {
b.mergeScale(bo);
b.setCount(b.getCount() + bo.getCount());
break;
}
} else {
if (b.getId() == bo.getId()) {
b.mergeScale(bo);
b.setCount(b.getCount() + bo.getCount());
break;
}
}
}
}
}
public Iterator<DataBlock> getIterator() {
return new DelegateIterator<DataBlock>() {
private int index;
@Override
protected Iterator<DataBlock> nextIterator() {
if (index == 0) {
index++;
return blocks.iterator();
} else if (index == 1) {
index++;
if (exit != null) {
return exit.getIterator();
} else {
return nextIterator();
}
} else {
return null;
}
}
};
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
Collection<DataBlock> blocks = blocks();
int blocksNum = 0;
for (DataBlock b : blocks) {
if (!(b instanceof DataBlockTarget)) {
++blocksNum;
}
}
out.writeShort(blocksNum);
for (DataBlock b : blocks) {
if (b instanceof DataBlockTarget) {
// for some reason we can _create_ data with DataBlockTarget in blockMap, but we do not _save_ and _read_ them in XML
continue;
}
if (b instanceof DataBlockCatch) {
out.write(0);
} else if (b instanceof DataBlockFallThrough) {
out.write(1);
} else if (b instanceof DataBlockMethEnter) {
out.write(2);
} else {
throw new IOException("BasicBlock.writeObject - Unknown dataBlock class " + b.getClass().getName() + ".");
}
b.writeObject(out);
}
if (exit != null) {
out.writeBoolean(true);
if (exit instanceof DataExitSimple) {
out.write(1);
} else if (exit instanceof DataBranchCond) {
out.write(2);
} else if (exit instanceof DataBranchGoto) {
out.write(3);
} else if (exit instanceof DataBranchSwitch) {
out.write(4);
} else {
throw new IOException("BasicBlock.writeObject - Unknown dataExit class " + exit.getClass().getName() + ". Please contact jcov_dev_ww@oracle.com");
}
exit.writeObject(out);
} else {
out.writeBoolean(false);
}
// fallenInto.writeObject(out); not needed?
}
BasicBlock(int rootId, DataInput in) throws IOException {
super(rootId, in);
int blockNum = in.readShort();
blocks = Collections.newSetFromMap(new IdentityHashMap<>());
int code;
for (int i = 0; i < blockNum; ++i) {
code = in.readByte();
switch (code) {
case 0:
blocks.add(new DataBlockCatch(rootId, in));
break;
case 1:
blocks.add(new DataBlockFallThrough(rootId, in));
break;
case 2:
blocks.add(new DataBlockMethEnter(rootId, in));
break;
// for some reason we can _create_ data with DataBlockTarget in blockMap, but we do not _save_ and _read_ them in XML
default:
throw new IOException("DataBlock with unknown code in BasicBlock " + code);
}
}
if (in.readBoolean()) {
code = in.readByte();
switch (code) {
case 1:
exit = new DataExitSimple(rootId, in);
break;
case 2:
exit = new DataBranchCond(rootId, in);
break;
case 3:
exit = new DataBranchGoto(rootId, in);
break;
case 4:
exit = new DataBranchSwitch(rootId, in);
break;
default:
throw new IOException("DataExit with unknown code in BasicBlock " + code);
}
}
}
} | 10,759 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockCatch.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlockCatch.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.IOException;
/**
*
* @author Robert Field
*/
public class DataBlockCatch extends DataBlock {
/**
* Creates a new instance of DataBlockCatch
*/
public DataBlockCatch(int rootId) {
super(rootId);
}
public DataBlockCatch(int rootId, int slot, boolean attached, long count) {
super(rootId, slot, attached, count);
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.CATCH;
}
DataBlockCatch(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 1,859 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataMethod.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataMethod.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.instrument.asm.ASMModifiers;
import com.sun.tdk.jcov.util.NaturalComparator;
import com.sun.tdk.jcov.data.Scale;
import com.sun.tdk.jcov.util.Utils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Parent for all method data classes. Keeps base information about method
* itself.
*
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public abstract class DataMethod extends DataAnnotated implements Comparable<DataMethod>,
Iterable<DataBlock> {
/**
* Parent DataClass which is containing this object
*/
protected final DataClass parent;
/**
* Container for method access code
*/
protected final Modifiers access;
/**
* Method name
*/
protected final String name;
/**
* VM-formed signature
*/
protected final String vmSig;
/**
* Method signature
*/
protected final String signature;
/**
* Exceptions which are thrown from this method
*/
protected final String[] exceptions;
/**
* Information about position in source file
*/
protected List<LineEntry> lineTable;
/**
* Check whether this DataMethod is configured to differ elements - classes
* vs interfaces<br/> False always
*/
private final boolean differentiateMethods;
/**
* Creates new DataMethod instance<br> Warning, this constructor adds
* created object to <b>k</b> DataClass. Do not use this constructor in
* iterators.
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
* @param differentiateMethods
*/
DataMethod(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions,
final boolean differentiateMethods) {
super(k.rootId);
this.parent = k;
this.access = new ASMModifiers(access);
this.name = name;
this.vmSig = desc;
this.signature = signature;
this.exceptions = exceptions;
this.differentiateMethods = differentiateMethods; // always false at the moment
k.addMethod(this);
}
/**
* Creates new DataMethod instance<br> Warning, this constructor adds
* created object to <b>k</b> DataClass. Do not use this constructor in
* iterators.
*
*/
protected DataMethod(DataMethod other) {
super(other.rootId);
this.parent = other.parent;
this.access = other.access;
this.name = other.name;
this.vmSig = other.vmSig;
this.signature = other.signature;
this.exceptions = other.exceptions;
this.differentiateMethods = other.differentiateMethods; // always false at the moment
}
/**
* @return exceptions thrown by this method
*/
public String[] getExceptions() {
return exceptions;
}
/**
* @return method name
*/
public String getName() {
return name;
}
/**
* @return full method name in format /package1/package2/Class.method +
* vmSig
*/
public String getFullName() {
return parent.getFullname() + "." + name + vmSig;
}
/**
* @return class containing this method
*/
public DataClass getParent() {
return parent;
}
/**
* @return method signature
*/
public String getSignature() {
return signature;
}
/**
* @return method VM signature
*/
public String getVmSignature() {
return vmSig;
}
/**
* @return human readable method signature with arguments and return type
* (ret name(arg1,arg2,arg3))
*/
public String getFormattedSignature() {
return Utils.convertVMtoJLS(name, vmSig);
}
/**
* Get methods access code
* @return methods access code
*/
public int getAccess() {
return access.access();
}
public Modifiers getModifiers() { return access; }
/**
* Get this method`s access flags as String array
*
* @return this method`s access flags as String array
*/
public String[] getAccessFlags() {
return accessFlags(access);
}
/**
* Check whether <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*
* @see #getAccess()
* @return true if <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*/
@Deprecated
public boolean isPublic() {
return isPublicAPI();
}
/**
* Check whether <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*
* @see #getAccess()
* @return true if <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*/
public boolean isPublicAPI() {
return access.isPublic() || access.isProtected();
}
/**
* Check whether <b>access</b> field has ACC_ABSTRACT flag
*
* @see #getAccess()
* @return true if <b>access</b> field has ACC_ABSTRACT flag
*/
@Deprecated
public boolean isAbstract() {
return access.isAbstract();
}
/**
* Checks whether this method has 'private' modifier
*
* @return true if method is private
*/
@Deprecated
public boolean hasPrivateModifier() {
return access.isPrivate();
}
/**
* Checks whether this method has 'public ' modifier
*
* @return true if method is public
*/
@Deprecated
public boolean hasPublicModifier() {
return access.isPublic();
}
/**
* Checks whether this method has 'protected' modifier
*
* @return true if method is protected
*/
@Deprecated
public boolean hasProtectedModifier() {
return access.isProtected();
}
/**
* Checks whether this method has 'abstract' modifier
*
* @return true if method is abstract
*/
@Deprecated
public boolean hasAbstractModifier() {
return access.isAbstract();
}
/**
* Checks whether this method has 'static' modifier
*
* @return true if method is static
*/
@Deprecated
public boolean hasStaticModifier() {
return access.isStatic();
}
/**
* Checks whether this method has 'native' modifier
*
* @return true if method is native
*/
@Deprecated
public boolean hasNativeModifier() {
return access.isNative();
}
/**
* Checks whether this method has specified modifier
*
* @return true if method has specified modifier
* @see DataMethod#getAccess()
*/
@Deprecated
public boolean hasModifier(int modifierCode) {
return access.is(modifierCode);
}
/**
* Check whether this method was hit. When DataMethod is attached - data is
* directly gotten from Collect class<br/><br/>
*
* Don't use it directly with DataMethodWithBlocks - it contains several
* block. Loop through it's blocks instead.
*
* @return true if this method was hit
*/
public abstract boolean wasHit();
/**
* Check how many times this method was hit. When DataMethod is attached -
* data is directly gotten from Collect class<br/><br/>
*
* Don't use it directly with DataMethodWithBlocks - it contains several
* block. Loop through it's blocks instead. The first - MethEnter
*
* @return times this method was hit
*/
public abstract long getCount();
/**
* Set count of hits. If DataMethod is attached - data is directly written
* to Collect class<br/><br/>
*
* Don't use it directly with DataMethodWithBlocks - it contains several
* block. Loop through it's blocks instead.
*
* @param count
*/
public abstract void setCount(long count);
/**
* Get scales information of this method. It's a bit mask telling which
* testrun hit this method<br/><br/>
*
* Don't use it directly with DataMethodWithBlocks - it contains several
* block. Loop through it's blocks instead.
*
* @return scales information of this method
*/
public abstract Scale getScale();
/**
* -1 means that there is no id in this method
*
* @return id assigned to this method (or to the first block of this method
* - methenter)
*/
public abstract int getSlot();
public abstract DataMethod clone(DataClass newClass, int newAccess, String newName);
@Override
public boolean equals(Object o) {
if (!(o instanceof DataMethod)) {
return false;
}
DataMethod meth = (DataMethod) o;
return parent.equals(meth.parent) && name.equals(meth.name) && vmSig.equals(meth.vmSig);
}
@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (this.parent != null ? this.parent.hashCode() : 0);
hash = 17 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 17 * hash + (this.vmSig != null ? this.vmSig.hashCode() : 0);
return hash;
}
@Override
public String toString() {
return super.toString() + "-" + name;
}
/**
* @return false
*/
public boolean hasCRT() {
return false;
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
public String kind() {
if (differentiateMethods) {
if (name.equals("<init>")) {
return XmlNames.CONSTRUCTOR;
} else if (name.equals("<clinit>")) {
return XmlNames.CLASS_INIT;
}
}
return XmlNames.METHOD;
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
public void xmlGen(XmlContext ctx) {
if (ctx.showAbstract || !access.isAbstract()) {
super.xmlGen(ctx);
}
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
void xmlAttrs(XmlContext ctx) {
ctx.attrNormalized(XmlNames.NAME, name);
ctx.attr(XmlNames.VMSIG, vmSig);
xmlAccessFlags(ctx, access);
ctx.attr(XmlNames.ACCESS, access.access());
if (!differentiateMethods) {
if (name.equals("<init>")) {
ctx.attr(XmlNames.CONSTRUCTOR, true);
} else if (name.equals("<clinit>")) {
ctx.attr(XmlNames.CLASS_INIT, true);
}
}
if (signature != null) {
ctx.attrNormalized(XmlNames.SIGNATURE, signature);
}
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
void xmlBody(XmlContext ctx) {
if (ctx.showLineTable && lineTable != null) {
xmlLineTable(ctx);
}
}
/**
* XML Generation. Not supposed to use outside.
*/
void xmlLineTable(XmlContext ctx) {
ctx.indent();
ctx.print("<lt>");
for (LineEntry pair : lineTable) {
ctx.print(pair.bci + "=" + pair.line + ";");
}
ctx.println("</lt>");
}
/**
* Add information about position in source file
*
* @param bci
* @param line
*/
public void addLineEntry(int bci, int line) {
if (lineTable == null) {
lineTable = new ArrayList<LineEntry>();
}
lineTable.add(new LineEntry(bci, line));
}
/**
* Keeps information about ranges in source file
*/
public static class LineEntry {
/**
* Instruction number (position) in bytecode
*/
public int bci;
/**
* Line number in source code
*/
public int line;
LineEntry(int bci, int line) {
this.bci = bci;
this.line = line;
}
}
/**
* @return information about where this method is written in sources
*/
public List<LineEntry> getLineTable() {
return lineTable;
}
public int compareTo(DataMethod method) {
return NaturalComparator.INSTANCE.compare(this.name, method.getName());
}
/**
* Checks whether this method is compatible with <b>other</b>
*
* @param other
* @param trace
* @throws MergeException
*/
public abstract void checkCompatibility(DataMethod other, String trace) throws MergeException;
/**
* Merges information from <b>other</b> to this DataMethod. <br/> This only
* sums hit count and scales - any difference in method structure is an
* error
*
* @param other
*/
public abstract void merge(DataMethod other);
/**
* <p> Decode method`s access flags as String array </p> <p> Defender
* methods (interface-default - Lambda project) have the same OpCode as
* 'interface' so they should be marked as 'defender'. </p> <p> 'volatile'
* and 'transient' flags are ignored </p> <p> Note that not all flags are
* <i>written</i> or <i>read</i> into XML file </p>
*
* @param access
* @return method`s access flags as String array
*/
@Override
String[] accessFlags(Modifiers access) {
String[] as = super.accessFlags(access);
List<String> lst = new ArrayList();
for (String s : as) {
if (s.equals(XmlNames.A_INTERFACE)) {
lst.add(XmlNames.A_DEFENDER_METH);
} else {
if (!XmlNames.A_VOLATILE.equals(s) && !XmlNames.A_TRANSIENT.equals(s)) {
lst.add(s);
}
}
}
return lst.toArray(new String[lst.size()]);
}
/**
* @return list of <b>all</b> blocks included into this method. It can
* contain any block type.
*/
public abstract List<DataBlock> getBlocks();
/**
* Returns a list of <b>all</b> branches included into this method
* (DataExitSimple that represents just exit of the method is not included).
* DataMethodsEntryOnly (as method coverage) and DataMethodInvoked (abstract
* and native) will return Collections.EMPTY_LIST. <br/> <br/> Branch
* doesn't contain counts itself. But branch contains a set of
* DataBlockTargets which can contain counts. <br/>
*
* @return list of <b>all</b> branches included into this method.
* @see #getBranchTargets()
*/
public abstract List<DataBranch> getBranches();
/**
* Method can contain a number of branches. Each branch can contain any
* number of DataBlockTargets that can be counted. <br/>
*
* @return all DataBlocks included in all branches of this method
*/
public abstract List<DataBlockTarget> getBranchTargets();
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.writeUTF(name);
writeString(out, vmSig);
writeString(out, signature);
out.writeInt(access.access());
out.writeBoolean(differentiateMethods);
writeStrings(out, exceptions);
if (lineTable != null) {
out.writeShort(lineTable.size());
for (LineEntry line : lineTable) {
out.writeShort(line.bci);
out.writeShort(line.line);
}
} else {
out.writeShort(Short.MAX_VALUE);
}
}
DataMethod(DataClass parent, DataInput in) throws IOException {
super(parent.rootId, in);
this.parent = parent;
name = in.readUTF();
vmSig = readString(in);
signature = readString(in);
access = new ASMModifiers(in.readInt());
differentiateMethods = in.readBoolean();
exceptions = readStrings(in);
int len = in.readShort();
if (len != Short.MAX_VALUE) {
lineTable = new ArrayList<LineEntry>(len);
int bci, line;
for (int i = 0; i < len; ++i) {
bci = in.readShort();
line = in.readShort();
lineTable.add(new LineEntry(bci, line));
}
} else {
lineTable = null;
}
}
} | 17,485 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockFallThrough.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlockFallThrough.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.IOException;
/**
* DataBlockFallThrough
*
* @author Robert Field
*/
public class DataBlockFallThrough extends DataBlock {
public DataBlockFallThrough(int rootId) {
super(rootId);
}
public DataBlockFallThrough(int rootId, int slot, boolean attached, long count) {
super(rootId, slot, attached, count);
}
/**
* Does the previous block fall into this one?
*/
@Override
public boolean isFallenInto() {
return true;
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.FALL;
}
DataBlockFallThrough(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 1,987 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataRoot.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataRoot.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.data.ScaleOptions;
import com.sun.tdk.jcov.filter.MemberFilter;
import com.sun.tdk.jcov.instrument.reader.ReaderFactory;
import com.sun.tdk.jcov.instrument.reader.RootReader;
import com.sun.tdk.jcov.io.Reader;
import com.sun.tdk.jcov.runtime.Collect;
import com.sun.tdk.jcov.runtime.JCovXMLFileSaver;
import com.sun.tdk.jcov.tools.JcovVersion;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <p> DataRoot is the root for all coverage data. It contains information about
* covered product hierarchy - all packages, classes, methods and blocks could
* be retrieved from DataRoot. </p> <p> It's also used for writing and reading
* XML files. Use DataRoot.read() method to read JCov data from XML file and
* DataRoot.write() method to write an XML file. </p>
*
* @see DataRoot#read(java.lang.String)
* @see DataRoot#read(java.lang.String, boolean,
* com.sun.tdk.jcov.filter.MemberFilter)
* @see DataRoot#write(java.lang.String,
* com.sun.tdk.jcov.instrument.InstrumentationOptions.MERGE)
* @author Robert Field
* @author Sergey Borodin
* @author Dmitry Fazunenko
* @author Andrey Titov
*/
public class DataRoot extends DataAbstract {
/**
* Total slot count
*/
private int count;
/**
* Coverage generator args (used for Agent mostly)
*/
private String args;
/**
* XML file containing this DataRoot
*/
private String storageFileName;
/**
* True when this DataRoot is synchronized with Collect class. <br/> This
* means that this DataRoot is getting hit counts from Collect class and not
* from inside storage.
*/
private boolean attached = false;
/**
* Packages registered in this DataRoot
*/
private final Map<String, DataPackage> packages;
/**
* Scales information
*/
protected ScaleOptions scaleOpts = new ScaleOptions();
/**
* Instrumentation information
*/
protected InstrumentationParams params;
/**
* All instances of DataRoots (for attaching&merging capabilities)
*/
private static Map<Integer, DataRoot> instances = new HashMap();
private static volatile int instanceCount = 0;
private List<Integer> secondaryIDs = new LinkedList<Integer>();
/**
* Acceptor API
*/
protected MemberFilter acceptor;
/**
* Reading API
*/
protected ReaderFactory rf;
private TreeMap<String, String> props;
private static final Logger logger;
static {
logger = Logger.getLogger(DataRoot.class.getName());
}
/**
* Every DataRoot has it's own ID and is stored in static library.
* <br/><br/>
*
* To remove DataRoot use destroy()
*
* @param i DataRoot ID
* @return Find the DataRoot by ID
* @see #destroy()
*/
public static DataRoot getInstance(int i) {
return instances.get(i);
}
/**
* <p> Create empty DataRoot. </p> <p> Every DataRoot has it's own ID and is
* stored in static library. </p> <p> To remove DataRoot use destroy() </p>
* <p> To load DataRoot from a file use read() method </p>
*
* @param params Parameters this coverage DataRoot was collected with
* @see #destroy()
* @see #read(java.lang.String)
* @see #read(java.lang.String, boolean,
* com.sun.tdk.jcov.filter.MemberFilter)
*/
public DataRoot(InstrumentationParams params) {
this("", true, params);
}
/**
* Creates a new instance of DataRoot<br/><br/>
*
* Every DataRoot has it's own ID and is stored in static library.
* <br/><br/>
*
* To remove DataRoot use destroy() <p> To load DataRoot from a file use
* read() method </p>
*
* @param args Command line arguments used to collect this coverage. Mostly
* used with Agent
* @param params Parameters this coverage DataRoot was collected with
* @see #destroy()
* @see #read(java.lang.String)
* @see #read(java.lang.String, boolean,
* com.sun.tdk.jcov.filter.MemberFilter)
*/
public DataRoot(String args, InstrumentationParams params) {
this(args, true, params);
}
/**
* Creates empty DataRoot object. Take care of initializing
* InstrumentationParams (e.g. in XML reading)<br/><br/>
*
* Every DataRoot has it's own ID and is stored in static library.
* <br/><br/>
*
* To remove DataRoot use destroy() <p> To load DataRoot from a file use
* read() method </p>
*
* @param args Command line arguments used to collect this coverage. Mostly
* used with Agent
* @param attached An attached DataRoot is synchronized with Collect class
* so that it gets (and stores) hit count directly from Collect
* @see #destroy()
* @see #read(java.lang.String)
* @see #read(java.lang.String, boolean,
* com.sun.tdk.jcov.filter.MemberFilter)
*/
public DataRoot(String args, boolean attached) {
super(instanceCount++);
instances.put(rootId, this);
this.args = args;
this.packages = new HashMap<String, DataPackage>();
this.attached = attached;
this.props = new TreeMap<String, String>();
}
/**
* Creates empty DataRoot object.<br/><br/>
*
* Every DataRoot has it's own ID and is stored in static library.
* <br/><br/>
*
* To remove DataRoot use destroy()
*
* @param args Command line arguments used to collect this coverage. Mostly
* used with Agent
* @param attached An attached DataRoot is synchronized with Collect class
* so that it gets (and stores) hit count directly from Collect
* @param params Parameters this coverage DataRoot was collected with
* @see #destroy()
*/
public DataRoot(String args, boolean attached, InstrumentationParams params) {
this(args, attached);
this.params = params;
}
/**
* Removes this DataRoots from the instances<br/><br/>
*
* Every DataRoot has it's own ID and is stored in static library.
*/
public void destroy() {
if (rootId == -1) {
return; // already removed
}
instances.remove(rootId);
for (int i : secondaryIDs) {
instances.remove(i);
}
rootId = -1;
}
/**
* @return Command line arguments used to collect this coverage. Mostly used
* with Agent
*/
public String getArgs() {
return args;
}
/**
* Set command line arguments used to collect this coverage. Mostly used
* with Agent
*
* @param args command line arguments used to collect this coverage
*/
public void setArgs(String args) {
this.args = args;
}
/**
* Get slot count. If this DataRoot is attached - data is taken directly
* from Collect
*
* @return the count of slots
*/
public int getCount() {
if (!attached) {
return count;
} else {
return Collect.slotCount();
}
}
/**
* Set slot count. <br/> Doesn't care about attached status.
*
* @param count
*/
public void setCount(int count) {
this.count = count;
}
/**
* Set the options of scales
*
* @param scaleOpts new options of scales
*/
public void setScaleOpts(ScaleOptions scaleOpts) {
this.scaleOpts = scaleOpts;
}
/**
* @return the options of scales
*/
public ScaleOptions getScaleOpts() {
return scaleOpts;
}
/**
* Set the filename of XML file storing this DataRoot
*
* @param fileName XML file storing this DataRoot
*/
public void setStorageFileName(String fileName) {
storageFileName = fileName;
}
/**
* @return the filename of XML file storing this DataRoot
*/
public String getStorageFileName() {
return storageFileName;
}
/**
* Set the parameters of this DataRoot
*
* @param params Parameters this coverage DataRoot was collected with
*/
public void setParams(InstrumentationParams params) {
this.params = params;
}
/**
* Get the parameters of this DataRoot
*
* @return Parameters this coverage DataRoot was collected with
*/
public InstrumentationParams getParams() {
return params;
}
/**
* Attached means that this DataRoot is synchronized with Collect object.
* <br/> This means that hit counts are read from Collect and not from
* DataRoot hierarchy
*
* @return true when attached
*/
public boolean isAttached() {
return attached;
}
/**
* Acceptor is used when adding a class to the DataRoot
*
* @param acceptor acceptor for this DataRoot
*/
public void setAcceptor(MemberFilter acceptor) {
this.acceptor = acceptor;
}
/**
* Acceptor is used when adding a class to the DataRoot
*
* @return acceptor for this DataRoot
*/
public MemberFilter getAcceptor() {
return acceptor;
}
/**
* Set reader factory used to read the XML. Not supposed to be used outside.
*
* @param rf reader factory (StAX or JAXB)
*/
public void setReaderFactory(ReaderFactory rf) {
this.rf = rf;
}
/**
* Get reader factory used to read the XML. Not supposed to be used outside.
*
* @return reader factory (StAX or JAXB)
*/
public ReaderFactory getReaderFactory() {
return rf;
}
/**
* Get packages registered in this DataRoot. Packages are not stored
* hierarchically
*
* @return All packages map
* @see #packages
*/
public List<DataPackage> getPackages() {
ArrayList<DataPackage> packs = new ArrayList<DataPackage>(packages.size());
packs.addAll(packages.values());
return packs;
}
/**
* Find package by name. Creates new DataPackage instance if the package
* doesn't exist
*
* @param name
* @return package
*/
public DataPackage findPackage(String name) {
return findPackage(name, XmlNames.NO_MODULE);
}
/**
* Find package by name and module name. Creates new DataPackage instance if the package
* doesn't exist
*
* @param name
* @return package
*/
public DataPackage findPackage(String name, String moduleName) {
DataPackage pack = packages.get(name);
if (pack == null) {
pack = new DataPackage(rootId, name, moduleName);
packages.put(pack.getName(), pack);
}
return pack;
}
/**
* Find class by full classname (eg "foo/bar/MyClass")
*
* @param classname
* @return DataClass representing <code>classname</code> or null if not
* found
*/
public DataClass findClass(String classname) {
int i = classname.lastIndexOf('/');
String packname;
if (i > 0) {
packname = classname.substring(0, i);
classname = classname.substring(i);
} else {
packname = ROOT_PACKAGE;
}
DataPackage pack = packages.get(packname);
if (pack == null) {
return null;
}
return pack.findClass(classname);
}
/**
* Find class by full classname (eg "foo/bar/MyClass")
*
* @param classname
* @return package containing <code>classname</code> or null if not found
*/
public DataPackage findPackageForClass(String classname) {
int i = classname.lastIndexOf('/');
if (i > 0) {
classname = classname.substring(0, i);
} else {
classname = ROOT_PACKAGE;
}
return packages.get(classname);
}
/**
* Add a class to the DataRoot.
*
* @param clazz
*/
public void addClass(DataClass clazz) {
if (acceptor != null && !acceptor.accept(clazz)) {
return;
}
int slash = clazz.getFullname().lastIndexOf('/');
String pname =
(slash < 0)
? ""
: clazz.getFullname().substring(0, slash);
this.findPackage(pname, clazz.getModuleName()).addClass(clazz);
}
/**
* Add package info to this JCov data. It's also possible to add package
* with
* <code>findPackage()</code> method
*
* @param pack
* @see #findPackage(java.lang.String, java.lang.String)
*/
public void addPackage(DataPackage pack) {
packages.put(pack.getName(), pack);
}
/**
* @return list of all classes registered in this JCov data
*/
public List<DataClass> getClasses() {
LinkedList<DataClass> classes = new LinkedList<DataClass>();
for (DataPackage dp : packages.values()) {
classes.addAll(dp.getClasses());
}
return classes;
}
/**
* XML Generation. Not supposed to use outside.
*/
public String kind() {
return XmlNames.COVERAGE;
}
/**
* XML Generation
*/
@Override
public void xmlGen(XmlContext ctx) {
ctx.println("<?xml version='1.0' encoding='UTF-8'?>");
ctx.println();
super.xmlGen(ctx);
}
/**
* XML Generation
*/
@Override
void xmlAttrs(XmlContext ctx) {
ctx.println();
ctx.println(" xmlns='http://java.sun.com/jcov/namespace'");
ctx.println(" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'");
ctx.print(" xsi:schemaLocation='http://java.sun.com/jcov/namespace coverage.xsd'");
}
/**
* XML Generation
*/
@Override
void xmlBody(XmlContext ctx) {
xmlHead(ctx);
List<DataPackage> packList = new ArrayList<DataPackage>(packages.values());
Collections.sort(packList);
for (DataPackage pack : packList) {
pack.xmlGen(ctx);
}
}
/**
* XML Generation
*/
private void xmlHead(XmlContext ctx) {
if (attached) {
updateHead();
}
TimeZone gmt = TimeZone.getTimeZone("GMT");
Calendar calendar = new GregorianCalendar(gmt);
Date now = new Date();
calendar.setTime(now);
ctx.println();
ctx.indentPrintln("<" + XmlNames.HEAD + ">");
ctx.incIndent();
props.put("coverage.created.date", String.format(LOCALE_ROOT, "%tF", calendar));
props.put("coverage.created.time", String.format(LOCALE_ROOT, "%tT", calendar));
props.put("coverage.generator.name", "jcov");
props.put("coverage.generator.version", JcovVersion.jcovVersion);
props.put("coverage.generator.fullversion", JcovVersion.getJcovVersion());
props.put("coverage.spec.version", "1.3");
ctx.indentPrintln("<property " + XmlNames.NAME + "='coverage.generator.args' " + XmlNames.VALUE + "='" + args + "'/>");
ctx.indentPrintln("<property " + XmlNames.NAME + "='coverage.generator.mode' " + XmlNames.VALUE + "='" + params.getMode() + "'/>");
ctx.indentPrintln("<property " + XmlNames.NAME + "='coverage.generator.internal' " + XmlNames.VALUE + "='" + (params.isDetectInternal() ? "detect" : "include") + "'/>");
ctx.indentPrintln("<property " + XmlNames.NAME + "='coverage.generator.include' " + XmlNames.VALUE + "='" + InstrumentationOptions.concatRegexps(params.getIncludes()) + "'/>");
ctx.indentPrintln("<property " + XmlNames.NAME + "='coverage.generator.exclude' " + XmlNames.VALUE + "='" + InstrumentationOptions.concatRegexps(params.getExcludes()) + "'/>");
ctx.indentPrintln("<property " + XmlNames.NAME + "='coverage.generator.caller_include' " + XmlNames.VALUE + "='" + InstrumentationOptions.concatRegexps(params.getCallerIncludes()) + "'/>");
ctx.indentPrintln("<property " + XmlNames.NAME + "='coverage.generator.caller_exclude' " + XmlNames.VALUE + "='" + InstrumentationOptions.concatRegexps(params.getCallerExcludes()) + "'/>");
for (String key : props.keySet()) {
String value = props.get(key);
ctx.indentPrintln("<property " + XmlNames.NAME + "='" + key + "' " + XmlNames.VALUE + "='" + value + "'/>");
}
ctx.indentPrintln("<property " + XmlNames.NAME + "='dynamic.collected' " + XmlNames.VALUE + "='" + params.isDynamicCollect() + "'/>");
ctx.indentPrintln("<property " + XmlNames.NAME + "='id.count' " + XmlNames.VALUE + "='" + count + "'/>");
if (scaleOpts.getScaleSize() > 1) {
ctx.indentPrintln("<property " + XmlNames.NAME + "='scale.size' " + XmlNames.VALUE + "='" + scaleOpts.getScaleSize() + "'/>");
ctx.indentPrintln("<property " + XmlNames.NAME + "='scales.compressed' " + XmlNames.VALUE + "='" + scaleOpts.scalesCompressed() + "'/>");
}
ctx.decIndent();
ctx.indentPrintln("</" + XmlNames.HEAD + ">");
}
/**
* XML reading
*
* @throws FileFormatException
*/
public void readHeader() throws FileFormatException {
RootReader r = (RootReader) rf.getReaderFor(this);
r.readHeader(this);
}
/**
* Check whether this DataRoot is compatible with <b>other</b> one.
*
* @param other
* @param severity a level of error ignorance
* @param boe true means that checkCompatibility will stop on the first
* occurred critical (see <b>severity</b>) error
* @return Number of errors (if <b>boe</b> is set to true it can be only 1)
*/
public CompatibilityCheckResult checkCompatibility(DataRoot other, int severity, boolean boe) {
if (!checkHeaderCompatibility(other)) {
logger.log(Level.SEVERE, "Attempt to merge data of different data types: \n"
+ "expected {0}; found {1} (in XML header, property name \"coverage.generator.mode\")",
new Object[]{params.getMode().name(), params.getMode().name()});
return new CompatibilityCheckResult(1, 0);
}
int errors = 0;
int warnings = 0;
// checking java version after all checks as java mismatch is warning
String ver = other.props.get("java.runtime.version");
if (ver != null && !ver.equals(props.get("java.runtime.version"))) {
logger.log(Level.WARNING, "Java version differs in file {0}: {1}", new Object[]{other.storageFileName, ver});
warnings += 1;
}
for (DataPackage pOther : other.packages.values()) {
if (packages.containsKey(pOther.getName())) {
DataPackage p = packages.get(pOther.getName());
for (DataClass cl : pOther.getClasses()) {
DataClass c = p.findClass(cl.getName());
if (c != null) {
try {
errors += c.checkCompatibility(cl, other.getStorageFileName(), severity, boe);
} catch (MergeException e) {
logger.log(Level.SEVERE, "Error while merging class " + cl.getFullname(), e);
errors++;
if (boe) {
return new CompatibilityCheckResult(errors, warnings);
}
}
}
}
}
}
return new CompatibilityCheckResult(errors, warnings);
}
/**
* Creates scale information
*/
public void createScales() {
for (DataPackage p : getPackages()) {
for (DataClass c : p.getClasses()) {
for (DataMethod m : c.getMethods()) {
for (DataBlock b : m) {
b.expandScales(1, false);
}
}
for (DataField f : c.getFields()) {
for (DataBlock b : f) {
b.expandScales(1, false);
}
}
}
}
scaleOpts.setScaleSize(1);
}
/**
* Adds one new scale. Use this method when DataRoot receives several
* testruns during one VM run
*/
public void addScales() {
int newScaleSize = scaleOpts.getScaleSize() + 1;
for (DataPackage p : getPackages()) {
for (DataClass c : p.getClasses()) {
for (DataMethod m : c.getMethods()) {
for (DataBlock b : m) {
b.expandScales(newScaleSize, false, b.collectCount() - b.count);
}
}
for (DataField f : c.getFields()) {
for (DataBlock b : f) {
b.expandScales(newScaleSize, false, b.collectCount() - b.count);
}
}
}
}
scaleOpts.setScaleSize(newScaleSize);
}
/**
* Remove all scale information
*/
public void cleanScales() {
for (DataPackage p : getPackages()) {
for (DataClass c : p.getClasses()) {
for (DataMethod m : c.getMethods()) {
for (DataBlock b : m) {
b.cleanScale();
}
}
for (DataField f : c.getFields()) {
for (DataBlock b : f) {
b.cleanScale();
}
}
}
}
scaleOpts.setScaleSize(0);
}
/**
* Simple class containing error and warning number
*/
public static class CompatibilityCheckResult {
public int errors;
public int warnings;
public CompatibilityCheckResult(int errors, int warnings) {
this.errors = errors;
this.warnings = warnings;
}
}
public void mergeSorted(DataRoot other, boolean fullmerge) {
mergeHeader(other, fullmerge);
for (DataPackage otherPackage : other.packages.values()) {
if (!packages.containsKey(otherPackage.getName())) {
if (fullmerge) {
for (DataClass classOther : otherPackage.getClasses()) {
if (scaleOpts.needReadScales()) {
classOther.expandScales(scaleOpts.getScaleSize(), true);
addClass(classOther);
}
}
}
} else {
ListIterator<DataClass> thisClasses = packages.get(otherPackage.getName()).getClasses().listIterator();
ListIterator<DataClass> otherClasses = otherPackage.getClasses().listIterator();
DataClass thisClass = null, otherClass = null;
if (!thisClasses.hasNext()) {
while (otherClasses.hasNext()) {
otherClass = otherClasses.next();
if (fullmerge) {
if (scaleOpts.needReadScales()) {
otherClass.expandScales(scaleOpts.getScaleSize(), true);
}
thisClasses.add(otherClass);
thisClasses.next(); // skipping added class - preserving sorted state
}
}
} else {
while (otherClasses.hasNext()) {
otherClass = otherClasses.next();
thisClass = thisClasses.next();
int comp = thisClass.compareTo(otherClass);
while (thisClasses.hasNext() && comp < 0) {
thisClass = thisClasses.next();
comp = thisClass.compareTo(otherClass);
}
if (comp == 0) {
// found - merging class
thisClass.mergeSorted(otherClass);
} else if (comp > 0) {
// no such class in thisClasses
if (fullmerge) {
if (scaleOpts.needReadScales()) {
otherClass.expandScales(scaleOpts.getScaleSize(), true);
}
thisClasses.previous();
thisClasses.add(otherClass); // adding _before_ current. No need to skip new class as it was added before current and currect is still thisClass
}
} else {
// comp < 0 - thisClasses has no more elements - all that left are missing in thisClasses
if (fullmerge) {
if (scaleOpts.needReadScales()) {
otherClass.expandScales(scaleOpts.getScaleSize(), true);
}
thisClasses.add(otherClass);
thisClasses.next(); // skipping added class - preserving sorted state
while (otherClasses.hasNext()) {
otherClass = otherClasses.next();
if (scaleOpts.needReadScales()) {
otherClass.expandScales(scaleOpts.getScaleSize(), true);
}
thisClasses.add(otherClass);
thisClasses.next(); // skipping added class - preserving sorted state
}
}
break; // need to break as next iteration will call next() which will fail
}
}
}
}
}
}
/**
* Merges all information from <b>other</b> to this DataRoot<br/><br/>
*
* All hits are summed. If <b>fullmerge</b> is true all missing classes are
* copied as well<br/><br/>
*
* Note that in current implementation "other" DataRoot becomes invalid
* during the merge and destroyed at the end of method. This is done for
* efficiency, when we add classes into "this" from "other", to avoid clone
* operations.
*
* @param other
* @param fullmerge whether merge should add classes missing in this and
* existing in other. Should be false when merging with template - in this
* case filters and instrumentation method in the header will not be merged
* @throws MergeException
*/
public void merge(DataRoot other, boolean fullmerge) {
mergeHeader(other, fullmerge);
for (DataPackage pOther : other.packages.values()) {
if (!packages.containsKey(pOther.getName())) {
if (fullmerge) {
for (DataClass cl : pOther.getClasses()) {
if (scaleOpts.needReadScales()) {
cl.expandScales(scaleOpts.getScaleSize(), true, 0); // as now scales are created always in readDataRoot - no need to set last bit ON
}
addClass(cl);
}
}
} else {
DataPackage p = packages.get(pOther.getName());
if (p.getModuleName() == null || p.getModuleName().equals(XmlNames.NO_MODULE)) {
p.setModuleName(pOther.getModuleName());
}
for (DataClass cl : pOther.getClasses()) {
DataClass c = p.findClass(cl.getName());
if (c == null) {
if (fullmerge) {
if (scaleOpts.needReadScales()) {
cl.expandScales(scaleOpts.getScaleSize(), true, 0); // as now scales are created always in readDataRoot - no need to set last bit ON
}
p.addClass(cl);
}
} else {
c.merge(cl);
c.setModuleName(cl.getModuleName());
}
}
}
}
//To adjust scales for untouched classes
if (scaleOpts.needReadScales()) {
for (DataPackage p : packages.values()) {
for (DataClass cl : p.getClasses()) {
cl.expandScales(scaleOpts.getScaleSize(), false, 0); // untouched classes were not hit
}
}
}
instances.remove(other.rootId);
instances.put(other.rootId, this);
secondaryIDs.add(other.rootId);
other.rootId = -1; // to avoid remove problems (DataRoot.merge(dr); dr.destroy();)
}
/**
* Remove all blocks structure from this DataRoot (convert to method
* coverage)
*/
public void truncateToMethods() {
if (params.getMode() != InstrumentationOptions.InstrumentationMode.METHOD) {
for (DataPackage pack : packages.values()) {
for (DataClass clazz : pack.getClasses()) {
ListIterator<DataMethod> it = clazz.getMethods().listIterator();
while (it.hasNext()) {
DataMethod meth = it.next();
if (!(meth instanceof DataMethodEntryOnly)) {
it.set(new DataMethodEntryOnly(meth)); // should care of copying scales from blocks to methods
}
}
}
}
params = InstrumentationParams.setMode(params, InstrumentationOptions.InstrumentationMode.METHOD);
}
}
/**
* Merge JCov data with another one without looking into blocks structure
*
* @param other
* @param addmissing
*/
public void mergeOnSignatures(DataRoot other, boolean addmissing) {
mergeHeader(other, addmissing);
for (DataPackage otherPackage : other.packages.values()) {
DataPackage thisPackage = packages.get(otherPackage.getName());
if (thisPackage == null) { // other's package doesn't exist here - if fullmerge mode - need to add
if (addmissing) {
for (DataClass otherClass : otherPackage.getClasses()) {
if (scaleOpts.needReadScales()) {
otherClass.expandScales(scaleOpts.getScaleSize(), true, 0);
}
addClass(otherClass);
}
}
} else {
// package merging logic is in DataRoot as merging can affect scales
outer:
for (DataClass otherClass : otherPackage.getClasses()) {
for (DataClass thisClass : thisPackage.getClasses()) {
if (otherClass.getName().equals(thisClass.getName())) {
thisClass.mergeOnSignatures(otherClass);
continue outer;
}
}
// "continue outer" didn't happen - class not found
if (addmissing) {
if (scaleOpts.needReadScales()) {
otherClass.expandScales(scaleOpts.getScaleSize(), true, 0);
}
addClass(otherClass);
}
}
}
}
//To adjust scales for untouched classes
if (scaleOpts.needReadScales()) {
for (DataPackage p : packages.values()) {
for (DataClass cl : p.getClasses()) {
cl.expandScales(scaleOpts.getScaleSize(), false, 0); // untouched classes were not hit
}
}
}
instances.remove(other.rootId);
instances.put(other.rootId, this);
secondaryIDs.add(other.rootId);
}
private boolean checkHeaderCompatibility(DataRoot other) {
return params.getMode().equals(other.params.getMode());
}
private void mergeHeader(DataRoot other, boolean fullmerge) {
args = mergeArgs(args, other.args);
count = count > other.count ? count : other.count;
if (fullmerge) {
params = InstrumentationParams.mergeParams(params, other.params);
} else {
params = InstrumentationParams.mergeDetectInternalOnly(params, other.params);
}
if (scaleOpts.needReadScales()) {
scaleOpts.setScaleSize(scaleOpts.getScaleSize() + other.scaleOpts.getScaleSize());
}
}
private String mergeArgs(String args1, String args2) {
TreeSet<String> resSet = new TreeSet();
List<String> excludes = new LinkedList();
excludes.add(InstrumentationOptions.DSC_INCLUDE.name);
excludes.addAll(Arrays.asList(InstrumentationOptions.DSC_INCLUDE.aliases));
excludes.add(InstrumentationOptions.DSC_EXCLUDE.name);
excludes.addAll(Arrays.asList(InstrumentationOptions.DSC_EXCLUDE.aliases));
excludes.add(InstrumentationOptions.DSC_CALLER_INCLUDE.name);
excludes.addAll(Arrays.asList(InstrumentationOptions.DSC_CALLER_INCLUDE.aliases));
excludes.add(InstrumentationOptions.DSC_CALLER_EXCLUDE.name);
excludes.addAll(Arrays.asList(InstrumentationOptions.DSC_CALLER_EXCLUDE.aliases));
for (String s : excludes) {
s += "=";
}
String[][] arrays = {args1.split(","), args2.split(",")};
for (String[] arr : arrays) {
for (String s : arr) {
boolean toExclude = false;
for (String ex : excludes) {
if (s.startsWith(ex)) {
toExclude = true;
break;
}
}
if (!toExclude) {
resSet.add(s);
}
}
arr = args2.split(",");
}
String res = "";
for (String s : resSet) {
res += s + ",";
}
return res;
}
/**
* Synchronizes this DataRoot to Collect.slots - sets data from Collect to
* each element of DataRoot
*/
public void makeAttached() {
Collect.setSlot(count);
for (DataPackage p : packages.values()) {
for (DataClass clazz : p.getClasses()) {
for (DataMethod m : clazz.getMethods()) {
for (DataBlock b : m) {
b.attached = true;
b.setCount(Collect.countFor(b.slot) + b.count);
}
}
for (DataField fld : clazz.getFields()) {
for (DataBlock b : fld) {
b.attached = true;
b.setCount(Collect.countFor(b.slot) + b.count);
}
}
}
}
attached = true;
}
/**
* Make this DataRoot synchronized with Collect class. <br/><br/>
*
* This means that hit counts are read from Collect and not from DataRoot
* hierarchy
*/
public void attach() {
Collect.setSlot(count);
for (DataPackage p : packages.values()) {
for (DataClass clazz : p.getClasses()) {
for (DataMethod m : clazz.getMethods()) {
for (DataBlock b : m) {
b.attach();
}
}
for (DataField fld : clazz.getFields()) {
for (DataBlock b : fld) {
b.attach();
}
}
}
}
attached = true;
}
/**
* Make this DataRoot unsynchronized with Collect class.<br/><br/>
*
* This will copy all actual data from Collect to this DataRoot object
*/
public void detach() {
updateHead();
for (DataPackage p : packages.values()) {
for (DataClass clazz : p.getClasses()) {
for (DataMethod m : clazz.getMethods()) {
for (DataBlock b : m) {
b.detach();
}
}
for (DataField fld : clazz.getFields()) {
for (DataBlock b : fld) {
b.detach();
}
}
}
}
attached = false;
}
/**
* Copy actual hit data from Collect to this DataRoot object
*/
public void update() {
updateHead();
for (DataPackage p : packages.values()) {
for (DataClass clazz : p.getClasses()) {
for (DataMethod m : clazz.getMethods()) {
for (DataBlock b : m) {
b.update();
}
}
for (DataField fld : clazz.getFields()) {
for (DataBlock b : fld) {
b.update();
}
}
}
}
}
/**
* Update slot count. Not needed to do this now as count now is taken from
* Collect when attached
*/
private void updateHead() {
count = Collect.slotCount();
}
/**
* Removes classes rejected by the filter. For each accepted class applies
* the same filter to eliminate unwanted members.
*
* @param filter
*/
public void applyFilter(MemberFilter filter) {
if (filter == null) {
return;
}
for (String pack : packages.keySet()) {
DataPackage p = packages.get(pack);
p.applyFilter(filter);
}
List<String> toRemove = new LinkedList();
for (String pName : packages.keySet()) {
if (packages.get(pName).getClasses().isEmpty()) {
toRemove.add(pName);
}
}
for (String pack : toRemove) {
packages.remove(pack);
}
}
/**
* Remove duplicates in scales
*
* @param pairs
*/
public void illuminateDuplicatesInScales(ArrayList pairs) {
scaleOpts.setScaleSize(scaleOpts.getScaleSize() - pairs.size());
int newSize = scaleOpts.getScaleSize();
for (DataPackage p : packages.values()) {
for (DataClass clazz : p.getClasses()) {
for (DataMethod m : clazz.getMethods()) {
for (DataBlock b : m) {
b.illuminateDuplicatesInScales(newSize, pairs);
}
}
for (DataField fld : clazz.getFields()) {
for (DataBlock b : fld) {
b.illuminateDuplicatesInScales(newSize, pairs);
}
}
}
}
}
/**
* Check whether this DataRoot is configured to differ elements. E.g.
* constructors vs simple methods, classes vs interfaces<br/><br/> False
* always
*
* @return False always
*/
public boolean isDifferentiateElements() {
return false;
}
/**
* <p> Reads XML and retrieves DataRoot from it. Scales are read from the
* file or created if file doesn't contain scale information </p> <p> Uses
* Reader.readXML() </p>
*
* @param filename file to read
* @return DataRoot read from XML
* @throws FileFormatException if any problem reading XML occurs.
* @see com.sun.tdk.jcov.io.Reader
*/
public static DataRoot read(String filename) throws FileFormatException {
return Reader.readXML(filename);
}
/**
* <p> Reads XML and retrieves DataRoot from it. </p> <p> Uses
* Reader.readXML() </p>
*
* @param filename file to read
* @param readScales if true - JCov will read or create scales for this
* DataRoot
* @return DataRoot read from XML
* @throws FileFormatException if any problem reading XML occurs.
* @see com.sun.tdk.jcov.io.Reader
*/
public static DataRoot read(String filename, boolean readScales) throws FileFormatException {
return Reader.readXML(filename, readScales, null);
}
/**
* <p> Reads XML and retrieves DataRoot from it. </p> <p> Uses
* Reader.readXML() </p>
*
* @param filename file to read
* @param read_scales if true - JCov will read or create scales for this
* DataRoot
* @param filter allows to filter out some classes or specific methods and
* fields
* @return DataRoot read from XML
* @throws FileFormatException
* @see com.sun.tdk.jcov.io.Reader
* @see com.sun.tdk.jcov.filter.MemberFilter
*/
public static DataRoot read(String filename, boolean read_scales, MemberFilter filter) throws FileFormatException {
return Reader.readXML(filename, read_scales, filter);
}
/**
* Writes DataRoot to XML in <b>filename</b>
*
* @param filename file to write XML to
* @param mergeMode defines behavior when file exists (allows to merge data)
* @see com.sun.tdk.jcov.instrument.InstrumentationOptions.MERGE
*/
public void write(String filename, InstrumentationOptions.MERGE mergeMode) throws Exception {
JCovXMLFileSaver saver = new JCovXMLFileSaver(this, filename, null, mergeMode, false);
saver.saveResults();
}
/**
* Sort out all data
*/
public void sort() {
for (DataPackage p : packages.values()) {
p.sort();
}
}
/**
* Nonstandard options are stored in TreeMap. All it's containing would be
* saved to XML and binary
*
* @param props
*/
public void setXMLHeadProperties(TreeMap<String, String> props) {
this.props = props;
}
/**
* @return Nonstandard options tree
*/
public Map<String, String> getXMLHeadProperties() {
return props;
}
/**
* Writes DataRoot and all it's hierarchy to the stream
*
* @param out
* @throws IOException
*/
public void writeObject(DataOutput out) throws IOException {
params.writeObject(out);
scaleOpts.writeObject(out);
writeString(out, args);
out.writeShort(packages.size());
for (DataPackage p : packages.values()) {
p.writeObject(out);
}
out.write(props.size());
for (Map.Entry<String, String> e : props.entrySet()) {
out.writeUTF(e.getKey());
out.writeUTF(e.getValue());
}
}
/**
* Creates an instance of DataRoot reading it from the stream
*
* @param in
* @throws IOException
*/
public DataRoot(DataInput in) throws IOException {
super(instanceCount++);
try {
params = new InstrumentationParams(in);
scaleOpts = new ScaleOptions(in);
args = readString(in);
int packs = in.readShort();
packages = new HashMap<String, DataPackage>(packs);
for (int i = 0; i < packs; ++i) {
DataPackage p = new DataPackage(rootId, in);
packages.put(p.getName(), p);
}
int propsCount = in.readByte();
props = new TreeMap<String, String>();
for (int i = 0; i < propsCount; ++i) {
props.put(in.readUTF(), in.readUTF());
}
instances.put(rootId, this);
} catch (IOException e) {
--instanceCount;
throw e;
}
}
private static DataRoot mapXML(InputStream is, long[] counts) throws Exception {
DataRoot root = Reader.readXML(is);
root = applyCounts(root, counts, true);
return root;
}
public static DataRoot setCounts(DataRoot root, long[] counts) throws Exception {
return applyCounts(root, counts, false);
}
public static DataRoot mergeCounts(DataRoot root, long[] counts) throws Exception {
return applyCounts(root, counts, true);
}
private static DataRoot applyCounts(DataRoot root, long[] counts, boolean merge)
throws Exception {
for (DataPackage pack : root.getPackages()) {
for (DataClass clazz : pack.getClasses()) {
for (DataField fld : clazz.getFields()) {
long count = merge ? fld.getCount() : 0;
fld.setCount(count + counts[fld.getId()]);
}
for (DataMethod meth : clazz.getMethods()) {
if (meth instanceof DataMethodInvoked) {
DataMethodInvoked mi = (DataMethodInvoked) meth;
long count = merge ? mi.getCount() : 0;
mi.setCount(count + counts[mi.getId()]);
} else if (meth instanceof DataMethodEntryOnly) {
DataMethodEntryOnly me = (DataMethodEntryOnly) meth;
long count = merge ? me.getCount() : 0;
me.setCount(count + counts[me.getId()]);
} else {
DataMethodWithBlocks mb = (DataMethodWithBlocks) meth;
for (BasicBlock bb : mb.getBasicBlocks()) {
for (DataBlock db : bb.blocks()) {
long count = merge ? db.getCount() : 0;
db.setCount(count + counts[db.getId()]);
}
if (bb.exit instanceof DataBranch) {
DataBranch ba = (DataBranch) bb.exit;
for (DataBlockTarget tg : ba.branchTargets) {
long count = merge ? tg.getCount() : 0;
tg.setCount(count + counts[tg.getId()]);
}
}
}
}
}
}
}
return root;
}
private static transient Locale LOCALE_ROOT = new Locale("__", "", ""); // for jdk1.5 support
private static final transient String ROOT_PACKAGE = "";
} | 48,277 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockTargetGoto.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlockTargetGoto.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.IOException;
/**
* DataBlockTargetGoto
*
*
* @author Robert Field
*/
public class DataBlockTargetGoto extends DataBlockTarget {
public DataBlockTargetGoto(int rootId) {
super(rootId);
}
public DataBlockTargetGoto(int rootId, int slot, boolean attached, long count) {
super(rootId, slot, attached, count);
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.TG;
}
DataBlockTargetGoto(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 1,844 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockMethEnter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlockMethEnter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.IOException;
/**
* DataBlockMethEnter
*
* @author Robert Field
*/
public class DataBlockMethEnter extends DataBlock {
public DataBlockMethEnter(int rootId) {
super(rootId);
}
public DataBlockMethEnter(int rootId, int slot, boolean attached, long count) {
super(rootId, slot, attached, count);
}
/**
* Does the previous block fall into this one? Effectly yes, since this is
* the first block.
*/
@Override
public boolean isFallenInto() {
return true;
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.METHENTER;
}
DataBlockMethEnter(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 2,034 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SimpleBasicBlock.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/SimpleBasicBlock.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.data.Scale;
import com.sun.tdk.jcov.tools.OneElemIterator;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Iterator;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public class SimpleBasicBlock extends BasicBlock {
private final DataBlock block;
/**
* Creates new instance of SimpleBasicBlock
*
* @param rootId
*/
public SimpleBasicBlock(int rootId) {
this(rootId, -1, -1, true);
}
/**
* Creates new instance of SimpleBasicBlock
*
* @param rootId
* @param startBCI
*/
public SimpleBasicBlock(int rootId, int startBCI) {
this(rootId, startBCI, startBCI, true);
}
/**
* Creates new instance of SimpleBasicBlock
*
* @param rootId
* @param startBCI
* @param attached
*/
public SimpleBasicBlock(int rootId, int startBCI, int endBCI, boolean attached) {
super(rootId, startBCI, endBCI);
if (attached) {
block = startBCI == 0
? new DataBlockMethEnter(rootId)
: new DataBlock(rootId) {
public String kind() {
return XmlNames.BLOCK;
}
};
} else {
block = startBCI == 0
? new DataBlockMethEnter(rootId, 0, false, 0)
: new DataBlock(rootId, 0, false, 0) {
public String kind() {
return XmlNames.BLOCK;
}
};
}
block.setConcreteLocation(this);
add(block);
}
/**
* Get containing block`s ID
*
* @return
*/
public int getId() {
return block.getId();
}
/**
* Get containing block. Usually it's not needed to work directly with
* DataBlocks as all common information can be found from methods wasHit(),
* getCount() and getScale(). DataBlock itself contains information about
* it's type (DataBlockCond, DataBlockTargetGoto, ...)
*
* @return
*/
public DataBlock getBlock() {
return block;
}
/**
* Get containing block`s scale
*
* @return
*/
public Scale getScale() {
return block.scale;
}
@Override
public void xmlGen(XmlContext ctx) {
block.xmlGen(ctx);
}
@Override
boolean wasHit() {
return block.wasHit();
}
/**
* Get containing block`s hit count
*
* @return
*/
public long getCount() {
return block.getCount();
}
@Override
public void checkCompatibility(BasicBlock other) throws MergeException {
super.checkCompatibility(other);
if (!(other instanceof SimpleBasicBlock)) {
throw new MergeException("Block has other type than it's"
+ " merging copy, type is SimpleBasicBlock",
"",
MergeException.HIGH);
}
SimpleBasicBlock so = (SimpleBasicBlock) other;
if (!getDataRoot().getParams().isDynamicCollect() && !other.getDataRoot().getParams().isDynamicCollect()) {
if (getId() != so.getId()) {
throw new MergeException("Block has other id than it's"
+ " merging copy, id is " + getId(),
"",
MergeException.HIGH);
}
}
}
@Override
public void merge(BasicBlock other) {
SimpleBasicBlock so = (SimpleBasicBlock) other;
block.mergeScale(so.block);
block.setCount(getCount() + so.getCount());
}
@Override
public Iterator<DataBlock> getIterator() {
return new OneElemIterator(block);
}
@Override
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
if (block instanceof DataBlockMethEnter) {
out.write(1);
} else {
out.write(2);
}
block.writeObject(out);
}
SimpleBasicBlock(int rootId, DataInput in) throws IOException {
super(rootId, in);
byte code = in.readByte();
switch (code) {
case 1:
block = new DataBlockMethEnter(rootId, in);
break;
case 2:
block = new DataBlock(rootId, in) {
@Override
public String kind() {
return XmlNames.BLOCK;
}
};
default:
throw new IOException("DataBlock with unknown code in SimpleBasicBlock " + code);
}
}
} | 5,947 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataField.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataField.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.instrument.asm.ASMModifiers;
import com.sun.tdk.jcov.util.NaturalComparator;
import com.sun.tdk.jcov.data.Scale;
import com.sun.tdk.jcov.data.ScaleOptions;
import com.sun.tdk.jcov.runtime.Collect;
import com.sun.tdk.jcov.runtime.CollectDetect;
import com.sun.tdk.jcov.tools.OneElemIterator;
import com.sun.tdk.jcov.util.Utils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Keeps base information about field
*
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public class DataField extends DataAnnotated implements Comparable<DataField>,
Iterable<DataBlock> {
/**
* DataClass containing this field
*/
private final DataClass parent;
/**
* Container for field access code
*/
private final Modifiers access;
/**
* Field name
*/
private final String name;
/**
* VM-formed field signature
*/
private final String vmSig;
/**
* Field signature
*/
private String signature;
/**
* Field value
*/
private final Object value;
/**
* Coverage data assigned to this field
*/
private final DataBlock block;
/**
* Creates new DataField instance
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param value
*/
public DataField(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final Object value) {
this(k, access, name, desc, signature, value, -1);
}
/**
* Creates new DataField instance
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param value
* @param id
*/
public DataField(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final Object value,
int id) {
super(k.rootId);
this.parent = k;
this.access = new ASMModifiers(access);
this.name = name;
this.vmSig = desc;
this.signature = signature;
this.value = value;
boolean newSlot = (id == -1) ? true : false;
int slot = newSlot ? Collect.newSlot() : id;
this.block = new DataBlock(rootId, slot, newSlot, 0) {
public String kind() {
return XmlNames.FIELD;
}
@Override
protected boolean wasCollectHit() {
return CollectDetect.wasInvokeHit(DataAbstract.getInvokeID(k.getFullname(), name, desc));
}
@Override
protected long collectCount() {
return CollectDetect.invokeCountFor(DataAbstract.getInvokeID(k.getFullname(), name, desc));
}
@Override
protected void setCollectCount(long count) {
CollectDetect.setInvokeCountFor(DataAbstract.getInvokeID(k.getFullname(), name, desc), count);
}
};
k.addField(this);
}
public DataField clone(DataClass newClass, int newAccess, String newName) {
return new DataField(newClass, newAccess, newName, vmSig, this.signature, this.value);
}
/**
* Check whether this field was hit (read or written). When DataField is
* attached - data is directly gotten from Collect class
*
* @return true if this field was hit (read or written)
*/
boolean wasHit() {
return block.wasHit();
}
/**
* Get field ID
*
* @return field ID
*/
public int getId() {
return block.getId();
}
/**
* Check how many times this field was hit (read or written). When DataField
* is attached - data is directly gotten from Collect class
*
* @return times this field was hit
*/
public long getCount() {
return block.getCount();
}
/**
* Set count of hits. If DataField is attached - data is directly written to
* Collect class
*
* @param count
*/
public void setCount(long count) {
block.setCount(count);
}
/**
* Get scales information of this field. It's a bit mask telling which
* testrun hit this field
*
* @return scales information of this field
*/
public Scale getScale() {
return block.scale;
}
/**
* Set scales information of this field. It's a bit mask telling which
* testrun hit this field
*
* @param scale
*/
public void setScale(Scale scale) {
block.scale = scale;
}
/**
* @return the parent
*/
public DataClass getParent() {
return parent;
}
/**
* @return the access
*/
public int getAccess() {
return access.access();
}
public Modifiers getModifiers() { return access; }
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the vmSig
*/
public String getVmSig() {
return vmSig;
}
/**
* @return the value
*/
public Object getValue() {
return value;
}
/**
* @return the block
*/
public DataBlock getBlock() {
return block;
}
/**
* Check whether <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*
* @see #getAccess()
* @return true if <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*/
@Deprecated
public boolean isPublic() {
return isPublicAPI();
}
/**
* Check whether <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*
* @see #getAccess()
* @return true if <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*/
public boolean isPublicAPI() {
return access.isPublic() || access.isProtected();
}
/**
* Checks whether this field has 'private' modifier
*
* @return true if field is private
*/
@Deprecated
public boolean hasPrivateModifier() {
return access.isPrivate();
}
/**
* Checks whether this field has 'public ' modifier
*
* @return true if field is public
*/
@Deprecated
public boolean hasPublicModifier() {
return access.isPublic();
}
/**
* Checks whether this field has 'protected' modifier
*
* @return true if field is protected
*/
@Deprecated
public boolean hasProtectedModifier() {
return access.isProtected();
}
/**
* Checks whether this field has 'static' modifier
*
* @return true if field is static
*/
@Deprecated
public boolean hasStaticModifier() {
return access.isStatic();
}
/**
* Checks whether this field has specified modifier
*
* @return true if field has specified modifier
* @see DataField#getAccess()
*/
@Deprecated
public boolean hasModifier(int modifierCode) {
return access.is(modifierCode);
}
/**
* Get this field`s access flags as String array
*
* @return this field`s access flags as String array
*/
public String[] getAccessFlags() {
return accessFlags(access);
}
/**
* Get field signature
*
* @return field signature
*/
public String getSignature() {
return signature;
}
/**
* Set field signature
*/
public void setSignature(String signature) {
this.signature = signature;
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
public String kind() {
return block.kind();
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
public void xmlGen(XmlContext ctx) {
super.xmlGenBodiless(ctx);
}
// @Override
// void xmlBody(XmlContext ctx) {
// block.xmlBody(ctx);
// }
/**
* XML Generation. Not supposed to use outside.
*/
@Override
void xmlAttrs(XmlContext ctx) {
ctx.attrNormalized(XmlNames.NAME, name);
ctx.attr(XmlNames.VMSIG, vmSig);
xmlAccessFlags(ctx, access);
ctx.attr(XmlNames.ACCESS, access.access());
ctx.attr(XmlNames.ID, block.getId());
if (value != null) {
ctx.attr(XmlNames.VALUE, value);
}
if (signature != null) {
ctx.attrNormalized(XmlNames.SIGNATURE, signature);
}
if (block.getCount() > 0) {
ctx.attr(XmlNames.COUNT, block.getCount());
}
DataRoot r = DataRoot.getInstance(rootId);
if (block.scale != null) {
ScaleOptions opts = r.getScaleOpts();
StringBuffer sb = new StringBuffer(Utils.halfBytesRequiredFor(block.scale.size()));
sb.setLength(sb.capacity());
sb.setLength(block.scale.convertToChars(opts.scalesCompressed(), sb,
opts.getScaleCompressor()));
ctx.attr(XmlNames.SCALE, sb);
}
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof DataField)) {
return false;
}
DataField fld = (DataField) o;
return parent.equals(fld.parent) && name.equals(fld.name) && vmSig.equals(fld.vmSig);
}
@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (this.parent != null ? this.parent.hashCode() : 0);
hash = 17 * hash + (this.name != null ? this.name.hashCode() : 0);
hash = 17 * hash + (this.vmSig != null ? this.vmSig.hashCode() : 0);
return hash;
}
public int compareTo(DataField field) {
return NaturalComparator.INSTANCE.compare(this.name, field.getName());
}
/**
* Checks whether this field is compatible with <b>other</b>
*
* @param other
* @param trace
* @throws MergeException
*/
public void checkCompatibility(DataField other, String trace) throws MergeException {
if (!getDataRoot().getParams().isDynamicCollect() && !other.getDataRoot().getParams().isDynamicCollect()) {
if (block.getId() != other.block.getId()) {
throw new MergeException("Field has other id than it's"
+ " merging copy, expected " + block.getId() + "; found " + other.block.getId(),
trace, MergeException.CRITICAL);
}
}
}
/**
* Merges information from <b>other</b> to this DataField. <br/><br/> This
* only sums hit count and scales
*
* @param other
*/
public void merge(DataField other) {
block.mergeScale(other.block);
block.setCount(getCount() + other.getCount());
}
/**
* Get DataBlock iterator. DataBlock is the simplest hit and id storage.
* <br/><br/>
*
* Is a "one-element" iterator as field can have only 1 block
*
* @return DataBlock iterator
*/
public Iterator<DataBlock> iterator() {
return new OneElemIterator(block);
}
/**
* Decode fields`s access flags as String array
*
* @param access
* @return fields`s access flags as String array
*/
String[] accessFlags(Modifiers access) {
String[] as = super.accessFlags(access);
List<String> lst = new ArrayList();
for (String s : as) {
if (!s.equals(XmlNames.A_BRIDGE) && !s.equals(XmlNames.A_VARARGS)) {
lst.add(s);
}
}
return lst.toArray(new String[lst.size()]);
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.writeUTF(name);
writeString(out, signature);
writeString(out, vmSig);
out.writeInt(access.access());
// out.write(value); can't - object. Writing only name
if (value != null) {
out.writeBoolean(true);
out.writeUTF(value.getClass().getName());
} else {
out.writeBoolean(false);
}
block.writeObject(out);
}
DataField(final DataClass c, DataInput in) throws IOException {
super(c.rootId, in);
parent = c;
name = in.readUTF();
signature = readString(in);
vmSig = readString(in);
access = new ASMModifiers(in.readInt());
if (in.readBoolean()) {
value = in.readUTF(); // value
} else {
value = null;
}
block = new DataBlock(c.rootId) {
public String kind() {
return XmlNames.FIELD;
}
@Override
protected boolean wasCollectHit() {
return CollectDetect.wasInvokeHit(DataAbstract.getInvokeID(c.getFullname(), name, vmSig));
}
@Override
protected long collectCount() {
return CollectDetect.invokeCountFor(DataAbstract.getInvokeID(c.getFullname(), name, vmSig));
}
@Override
protected void setCollectCount(long count) {
CollectDetect.setInvokeCountFor(DataAbstract.getInvokeID(c.getFullname(), name, vmSig), count);
}
};
}
} | 14,739 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataMethodEntryOnly.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataMethodEntryOnly.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.data.Scale;
import com.sun.tdk.jcov.runtime.Collect;
import com.sun.tdk.jcov.tools.OneElemIterator;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* DataMethodEntryOnly serves for storing information about only entering into
* methods - eg Method coverage mode
*
* @author Robert Field
*/
public class DataMethodEntryOnly extends DataMethod implements Iterable<DataBlock> {
/**
* Method entry information
*/
private final DataBlockMethEnter entryBlock;
/**
* Creates a new instance of DataMethodEntryOnly<br> ID is generated<br>
* Warning, this constructor adds created object to <b>k</b> DataClass. Do
* not use this constructor in iterators.
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
*/
public DataMethodEntryOnly(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
this(k, access, name, desc, signature, exceptions, -1);
}
/**
* Creates a new instance of DataMethodEntryOnly<br> Warning, this
* constructor adds created object to <b>k</b> DataClass. Do not use this
* constructor in iterators.
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
* @param id
*/
public DataMethodEntryOnly(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions,
int id) {
super(k, access, name, desc, signature, exceptions, false);
boolean newData = (id == -1) ? true : false;
int slot = (newData) ? Collect.newSlot() : id;
entryBlock = new DataBlockMethEnter(rootId, slot, newData, 0) {
@Override
protected void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.ID, getId());
ctx.attr(XmlNames.COUNT, getCount());
printScale(ctx);
}
};
LocationConcrete loc = new LocationConcrete(0) {
public String kind() {
return "trash";
}
};
entryBlock.setConcreteLocation(loc);
}
/**
* Creates a new instance of DataMethodEntryOnly<br> Warning, this
* constructor adds created object to <b>k</b> DataClass. Do not use this
* constructor in iterators.
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
* @param id
* @param count
*/
public DataMethodEntryOnly(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions,
int id, long count) {
super(k, access, name, desc, signature, exceptions, false);
boolean newData = (id == -1) ? true : false;
int slot = (newData) ? Collect.newSlot() : id;
entryBlock = new DataBlockMethEnter(rootId, slot, newData, count) {
@Override
protected void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.ID, getId());
ctx.attr(XmlNames.COUNT, getCount());
printScale(ctx);
}
};
LocationConcrete loc = new LocationConcrete(0) {
public String kind() {
return "trash";
}
};
entryBlock.setConcreteLocation(loc);
}
/**
* Creates a new instance of DataMethodEntryOnly<br> Warning, this
* constructor adds created object to <b>k</b> DataClass. Do not use this
* constructor in iterators.
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
* @param id
* @param count
*/
public DataMethodEntryOnly(DataMethod other) {
super(other);
boolean newData = (other.getSlot() == -1) ? true : false;
int slot = (newData) ? Collect.newSlot() : other.getSlot();
entryBlock = new DataBlockMethEnter(rootId, slot, newData, other.getCount()) {
@Override
protected void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.ID, getId());
ctx.attr(XmlNames.COUNT, getCount());
printScale(ctx);
}
};
LocationConcrete loc = new LocationConcrete(0) {
public String kind() {
return "trash";
}
};
entryBlock.setConcreteLocation(loc);
}
@Override
public DataMethod clone(DataClass newClass, int newAccess, String newName) {
return new DataMethodEntryOnly(newClass, newAccess, newName, this.getVmSignature(), this.getSignature(), this.getExceptions());
}
/**
* Get the ID of this method entry
*
* @return
*/
public int getId() {
return entryBlock.getId();
}
@Override
public boolean wasHit() {
return entryBlock.wasHit();
}
@Override
public long getCount() {
return entryBlock.getCount();
}
@Override
public void setCount(long count) {
entryBlock.setCount(count);
}
/**
* Set the scale information of this method
*
* @param s
*/
public void setScale(String s) {
entryBlock.readScale(s);
}
public void setScale(Scale scale) {
entryBlock.scale = scale;
}
@Override
public Scale getScale() {
return entryBlock.scale;
}
@Override
public int getSlot() {
return entryBlock.slot;
}
// void readScale(String s) {
// if (s != null && s.length() > 0) {
// try {
// DataRoot r = DataRoot.getInstance(rootId);
// ScaleOptions opts = r.getScaleOpts();
// entryBlock.scale = new Scale(s.toCharArray(), s.length(),
// opts.getScaleSize(), opts.getScaleCompressor(), opts.scalesCompressed());
// } catch (JcovFileFormatException ex) {
// }
// }
// }
@Override
public void xmlGen(XmlContext ctx) {
super.xmlGenBodiless(ctx);
}
@Override
void xmlAttrs(XmlContext ctx) {
super.xmlAttrs(ctx);
entryBlock.xmlAttrs(ctx);
}
@Override
public void checkCompatibility(DataMethod other, String trace) throws MergeException {
if (!(other instanceof DataMethodEntryOnly)) {
throw new MergeException("Method has other type than it's"
+ " merging copy, expected DataMethodEntryOnly; found " + other.getClass().getSimpleName(),
trace, MergeException.CRITICAL);
}
DataMethodEntryOnly m = (DataMethodEntryOnly) other;
if (!getDataRoot().getParams().isDynamicCollect() && !other.getDataRoot().getParams().isDynamicCollect()) {
if (getId() != m.getId()) {
throw new MergeException("Method has other id than it's"
+ " merging copy, expected " + getId() + "; found " + m.getId(),
trace, MergeException.CRITICAL);
}
}
}
@Override
public void merge(DataMethod other) {
DataMethodEntryOnly m = (DataMethodEntryOnly) other;
entryBlock.mergeScale(m.entryBlock);
entryBlock.setCount(getCount() + m.getCount());
}
@Override
public Iterator<DataBlock> iterator() {
return new OneElemIterator(entryBlock);
}
@Override
public List<DataBlock> getBlocks() {
ArrayList<DataBlock> list = new ArrayList<DataBlock>(1);
list.add(entryBlock);
return list;
}
@Override
public List<DataBranch> getBranches() {
return Collections.EMPTY_LIST;
}
@Override
public List<DataBlockTarget> getBranchTargets() {
return Collections.EMPTY_LIST;
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
entryBlock.writeObject(out);
}
DataMethodEntryOnly(DataClass parent, DataInput in) throws IOException {
super(parent, in);
entryBlock = new DataBlockMethEnter(parent.rootId, in) {
@Override
protected void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.ID, getId());
ctx.attr(XmlNames.COUNT, getCount());
printScale(ctx);
}
};
}
} | 10,129 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBranchSwitch.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBranchSwitch.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* DataBranchSwitch
*
* @author Robert Field
*/
public class DataBranchSwitch extends DataBranch {
public DataBlockTargetDefault blockDefault;
public DataBranchSwitch(int rootId, int bciStart, int bciEnd) {
super(rootId, bciStart, bciEnd);
}
/**
* Creates a new instance of DataBranchSwitch
*/
public DataBranchSwitch(int rootId, int bciStart, int bciEnd, DataBlockTargetDefault blockDefault) {
this(rootId, bciStart, bciEnd);
this.blockDefault = blockDefault;
}
DataBlockTargetDefault blockDefault() {
return blockDefault;
}
public void setDefault(DataBlockTargetDefault blockDefault) {
this.blockDefault = blockDefault;
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.SWITHCH;
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
if (blockDefault != null) {
out.writeBoolean(true);
blockDefault.writeObject(out);
} else {
out.writeBoolean(false);
}
}
DataBranchSwitch(int rootId, DataInput in) throws IOException {
super(rootId, in);
if (in.readBoolean()) {
blockDefault = new DataBlockTargetDefault(rootId, in);
} else {
blockDefault = null;
}
}
} | 2,701 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataPackage.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataPackage.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.util.NaturalComparator;
import com.sun.tdk.jcov.filter.MemberFilter;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.Collections;
import java.util.Iterator;
/**
* DataPackage contains information about package hierarchy. Includes a list of
* classes.
*
* @see #classes
* @author Robert Field
*/
public class DataPackage extends DataAbstract implements Comparable<DataPackage> {
/**
* Name of associated package
*/
private final String name;
private String moduleName;
/**
* Classes in this package
*/
private final List<DataClass> classes;
/**
* Creates a new instance of DataPackage
*
* @param rootId
* @param name Associated package name
*/
public DataPackage(int rootId, String name, String modulename) {
super(rootId);
this.name = name;
this.moduleName = modulename;
this.classes = new LinkedList<DataClass>();
}
public void setModuleName(String moduleName){
this.moduleName = moduleName;
}
public String getModuleName(){
return moduleName;
}
/**
* Get associated package name
*
* @return associated package name
*/
public String getName() {
return name;
}
/**
* Add a class to this package. Doesn't check that class is unique in the
* package.
*
* @param k
*/
public void addClass(DataClass k) {
classes.add(k);
}
/**
*
* @return all classes in this package
*/
public List<DataClass> getClasses() {
return classes;
}
/**
* Get DataClass by name
*
* @param className
* @return DataClass with name <b>className</b> or null of this DataPackage
* doesn't contain this class
*/
public DataClass findClass(String className) {
for (DataClass cl : classes) {
if (cl.getName().equals(className)) {
return cl;
}
}
return null;
}
public boolean removeClass(DataClass k) {
return classes.remove(k);
}
public boolean removeClass(String k) {
if (k == null) {
return false;
}
Iterator<DataClass> it = classes.iterator();
while (it.hasNext()) {
if (it.next().getName().equals(k)) {
it.remove();
return true;
}
}
return false;
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
public String kind() {
return XmlNames.PACKAGE;
}
/**
* XML Generation
*/
@Override
void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.NAME, name.replace('/', '.'));
ctx.attr(XmlNames.MODULE_NAME, moduleName);
}
/**
* XML Generation
*/
@Override
void xmlBody(XmlContext ctx) {
Collections.sort(classes);
for (DataClass k : classes) {
k.xmlGen(ctx);
}
}
public int compareTo(DataPackage pack) {
return NaturalComparator.INSTANCE.compare(this.name, pack.getName());
}
/**
* Removes classes rejected by the filter. For each accepted class applies
* the same filter to eliminate unwanted members.
*
* @param filter
*/
public boolean applyFilter(MemberFilter filter) {
Iterator<DataClass> it = classes.iterator();
while (it.hasNext()) {
DataClass clazz = it.next();
if (!filter.accept(clazz)) {
it.remove();
} else {
clazz.applyFilter(filter);
}
}
return classes.isEmpty();
}
/**
* Sort out all classes in this package
*/
public void sort() {
Collections.sort(classes);
for (DataClass c : classes) {
c.sort();
}
}
void writeObject(DataOutput out) throws IOException {
out.writeUTF(name);
out.writeUTF(moduleName);
out.writeShort(classes.size());
for (DataClass dc : classes) {
dc.writeObject(out);
}
}
DataPackage(int rootID, DataInput in) throws IOException {
super(rootID);
name = in.readUTF();
moduleName = in.readUTF();
int classNum = in.readUnsignedShort();
classes = new ArrayList<DataClass>(classNum);
for (int i = 0; i < classNum; ++i) {
classes.add(new DataClass(rootID, in));
}
}
} | 5,898 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockTarget.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlockTarget.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.IOException;
/**
* <p> DataBlockTarget is an abstract class for all branch target blocks:
* DataBlockTargetCase, DataBlockTargetDefault, DataBlockTargetCond and
* DataBlockTargetGoto. </p>
*
* @author Robert Field
* @see DataBlock
* @see DataBranch
*/
public abstract class DataBlockTarget extends DataBlock {
DataBranch enclosing;
DataBranch enclosing() {
return enclosing;
}
DataBlockTarget(int rootId) {
super(rootId);
}
DataBlockTarget(int rootId, int slot, boolean attached, long count) {
super(rootId, slot, attached, count);
}
void setEnclosing(DataBranch enclosing) {
this.enclosing = enclosing;
}
/**
* Yes, it is nested in a branch
*/
@Override
boolean isNested() {
return true;
}
/**
* XML Generation
*/
void xmlAttrsValue(XmlContext ctx) {
// for value printing, override this
}
@Override
protected void xmlAttrs(XmlContext ctx) {
super.xmlAttrs(ctx);
xmlAttrsValue(ctx);
}
DataBlockTarget(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 2,456 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlock.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlock.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.data.Scale;
import com.sun.tdk.jcov.data.ScaleOptions;
import com.sun.tdk.jcov.runtime.Collect;
import com.sun.tdk.jcov.util.Utils;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
/**
* <p> DataBlock is an abstract class storing location & count info about some
* instruction block in classfile. DataBlockTarget is an abstract class for all
* branch target blocks: DataBlockTargetCase, DataBlockTargetDefault,
* DataBlockTargetCond and DataBlockTargetGoto. </p> <p> DataBlocks are stored
* in BasicBlock (or just as DataBlockMethEnter in DataMethodEntryOnly) in a
* Map. DataBlockTargets are stored in a list in DataBranch. </p>
*
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public abstract class DataBlock extends LocationRef {
protected int slot;
protected long count;
protected boolean attached;
protected Scale scale;
/**
* Creates a new instance of DataBlock
*/
DataBlock(int rootId) {
super(rootId);
this.slot = Collect.newSlot();
attached = true;
}
DataBlock(int rootId, int slot, boolean attached, long count) {
super(rootId);
this.slot = slot;
this.attached = attached;
this.count = count;
if (attached) {
setCollectCount(count);
}
}
/**
* @return ID of this block
*/
public int getId() {
return slot;
}
/**
* Set ID of this block. Block ID is used to collect coverage (each
* instrumented block hits it's own slot)
*
* @param slot
*/
public void setId(int slot) {
this.slot = slot;
}
void attach() {
setCollectCount(count);
attached = true;
}
void detach() {
update();
attached = false;
}
void update() {
count = collectCount();
}
/**
* @return true if this block was hit at least once
*/
public boolean wasHit() {
if (attached) {
return wasCollectHit();
} else {
return count != 0;
}
}
/**
* @return the number of times this block was hit
*/
public long getCount() {
if (attached) {
return collectCount();
} else {
return count;
}
}
/**
* Set the count of times this block was hit
*
* @param count
*/
public void setCount(long count) {
if (attached) {
setCollectCount(count);
}
this.count = count;
}
/**
* Default implementations
*
*/
protected boolean wasCollectHit() {
return Collect.wasHit(slot);
}
protected long collectCount() {
return Collect.countFor(slot);
}
protected void setCollectCount(long count) {
Collect.setCountFor(slot, count);
}
boolean isNested() {
return false;
}
/**
* Does the previous block fall into this one? Override for blocks that are
* fallen into.
*/
public boolean isFallenInto() {
return false;
}
/**
* XML Generation
*/
@Override
protected void xmlAttrs(XmlContext ctx) {
super.xmlAttrs(ctx);
ctx.attr(XmlNames.ID, getId());
ctx.attr(XmlNames.COUNT, getCount());
printScale(ctx);
}
void printScale(XmlContext ctx) {
DataRoot r = DataRoot.getInstance(rootId);
if (scale != null) {
ScaleOptions opts = r.getScaleOpts();
StringBuffer sb = new StringBuffer(Utils.halfBytesRequiredFor(scale.size()));
sb.setLength(sb.capacity());
sb.setLength(scale.convertToChars(opts.scalesCompressed(), sb,
opts.getScaleCompressor()));
ctx.attr(XmlNames.SCALE, sb);
}
}
@Override
void xmlBody(XmlContext ctx) {
// if (cnt() > 0) {
// ctx.indentPrintln("<count>" + cnt() + "</count>");
// }
}
@Override
public void xmlGen(XmlContext ctx) {
xmlGenBodiless(ctx);
}
/**
* Not supposed to be used from outside
*
* @param s
*/
public void readScale(String s) {
if (s != null && s.length() > 0) {
try {
DataRoot r = DataRoot.getInstance(rootId);
ScaleOptions opts = r.getScaleOpts();
if (opts.needReadScales()) {
scale = new Scale(s.toCharArray(), s.length(),
opts.getScaleSize(), opts.getScaleCompressor(), opts.scalesCompressed());
}
} catch (FileFormatException ex) {
}
}
}
/**
* Increase size of scales assigned to this block. If count of this block is
* above zero - "1" is written to the end of scale
*
* @param newSize
* @param add_before where to put zeroes
*/
public void expandScales(int newSize, boolean add_before) {
scale = Scale.expandScale(scale, newSize, add_before, getCount());
}
/**
* Increase size of scales assigned to this block. If count is above zero -
* "1" is written to the end of scale
*
* @param newSize
* @param add_before where to put zeroes
* @param count
*/
public void expandScales(int newSize, boolean add_before, long count) {
scale = Scale.expandScale(scale, newSize, add_before, count);
}
void mergeScale(DataBlock other) {
boolean readScale = DataRoot.getInstance(rootId).getScaleOpts().needReadScales();
if (!readScale) {
return;
}
scale = Scale.merge(scale, other.scale, getCount(), other.getCount());
}
/**
* Not supposed to be used from outside
*
* @param new_size
* @param pairs
*/
public void illuminateDuplicatesInScales(int new_size, ArrayList pairs) {
scale = Scale.illuminateDuplicates(scale, new_size, pairs);
}
/**
* @return scale information of this block (null if scales were not
* generated)
* @see Scale
*/
public Scale getScale() {
return scale;
}
/**
* Remove all scale information
*/
public void cleanScale() {
try {
scale = new Scale(new char[0], 0, 0, null, false);
} catch (FileFormatException ignore) {
}
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.writeLong(getCount());
out.writeInt(slot);
if (scale != null) {
out.writeBoolean(true);
scale.writeObject(out);
} else {
out.writeBoolean(false);
}
}
DataBlock(int rootId, DataInput in) throws IOException {
super(rootId, in);
count = in.readLong();
slot = in.readInt();
if (in.readBoolean()) {
scale = new Scale(in);
} else {
scale = null;
}
}
} | 8,351 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataExit.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataExit.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Iterator;
/**
* DataExit
*
*
* @author Robert Field
*/
public abstract class DataExit extends LocationConcrete {
DataExit(int rootId, int bciStart, int bciEnd) {
super(rootId, bciStart, bciEnd);
}
public abstract Iterator<DataBlock> getIterator();
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
}
DataExit(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 1,811 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataExitSimple.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataExitSimple.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* DataExitSimple
*
* @author Robert Field
*/
public class DataExitSimple extends DataExit {
int opcode;
/**
* Creates a new instance of DataExitSimple
*/
public DataExitSimple(int rootId, int bciStart, int bciEnd, int opcode) {
super(rootId, bciStart, bciEnd);
this.opcode = opcode;
}
public String opcodeName() {
return Constants.opcNames[opcode];
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.EXIT;
}
@Override
public void xmlGen(XmlContext cxt) {
xmlGenBodiless(cxt);
}
@Override
protected void xmlAttrs(XmlContext ctx) {
super.xmlAttrs(ctx);
ctx.attr(XmlNames.OPCODE, opcodeName());
}
// void readDataFrom(XMLStreamReader parser, Map<LocationCoords, List<LocationRef>> refs,
// InstrumentationMode mode) throws XMLStreamException {
//// super.readDataFrom(parser, refs, mode);
// parser.nextTag(); //end exit
// }
@Override
public Iterator<DataBlock> getIterator() {
return new Iterator<DataBlock>() {
public boolean hasNext() {
return false;
}
public DataBlock next() {
throw new NoSuchElementException();
}
public void remove() {
}
};
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.write(opcode);
}
DataExitSimple(int rootId, DataInput in) throws IOException {
super(rootId, in);
opcode = in.readByte();
if (opcode < 0) {
opcode += 256;
}
}
} | 3,098 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
XmlNames.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/XmlNames.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
/**
*
* @author Sergey Borodin
*/
public class XmlNames {
public static final String HEAD = "head";
public static final String COVERAGE = "coverage";
public static final String PACKAGE = "package";
public static final String CLASS = "class";
public static final String INTERFACE = "interface";
public static final String METHOD = "meth";
public static final String CONSTRUCTOR = "cons";
public static final String CLASS_INIT = "clinit";
public static final String BLOCK = "bl";
public static final String METHENTER = "methenter";
public static final String FALL = "fall";
public static final String CATCH = "catch";
public static final String EXIT = "exit";
public static final String SWITHCH = "switch";
public static final String GOTO = "goto";
public static final String BRANCH = "br";
public static final String CASE = "case";
public static final String COND = "cond";
public static final String DEFAULT = "default";
public static final String TG = "tg";
public static final String FIELD = "fld";
public static final String NAME = "name";
public static final String SUPERNAME = "supername";
public static final String CHECKSUM = "checksum";
public static final String SIGNATURE = "signature";
public static final String VMSIG = "vmsig";
public static final String SOURCE = "source";
public static final String SUPER_INTERFACES = "superInterfaces";
public static final String OPCODE = "opcode";
public static final String FLAGS = "flags";
public static final String ACCESS = "access";
public static final String FX_ACCESS = "fxaccess";
public static final String ID = "id";
public static final String COUNT = "count";
public static final String SCALE = "scale";
public static final String VALUE = "val";
public static final String START = "s";
public static final String END = "e";
public static final String LENGTH = "length";
public static final String A_PUBLIC = "public";
public static final String A_PRIVATE = "private";
public static final String A_PROTECTED = "protected";
public static final String A_STATIC = "static";
public static final String A_FINAL = "final";
public static final String A_SYNCHRONIZED = "synchronized";
public static final String A_VOLATILE = "volatile";
public static final String A_BRIDGE = "bridge";
public static final String A_VARARGS = "varargs";
public static final String A_TRANSIENT = "transient";
public static final String A_NATIVE = "native";
public static final String A_INTERFACE = "interface";
public static final String A_DEFENDER_METH = "defender";
public static final String A_ABSTRACT = "abstract";
public static final String A_STRICT = "strict";
public static final String A_ANNOTATION = "annotation";
public static final String A_ENUM = "enum";
public static final String A_SYNTHETIC = "synthetic";
public static final String A_STATEMENT = "statement";
public static final String A_BLOCK = "block";
public static final String A_ASSIGNMENT = "assignment";
public static final String A_CONTROLLER = "controller";
public static final String A_TARGET = "target";
public static final String A_INVOKE = "invoke";
public static final String A_CREATE = "create";
public static final String A_BRANCHTRUE = "branchtrue";
public static final String A_BRANCHFALSE = "branchfalse";
public static final String LINETABLE = "lt";
public static final String RANGE = "range";
public static final String CRT = "crt";
public static final String CRT_POS = "pos";
public static final String CRT_LINE = "line";
public static final String CRT_COL = "col";
public static final String INNER_CLASS = "inner";
public static final String MODULE_NAME = "moduleName";
public static final String NO_MODULE = "no_module";
}
| 5,195 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Modifiers.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/Modifiers.java | /*
* Copyright (c) 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
public interface Modifiers {
boolean isPublic();
boolean isPrivate();
boolean isProtected();
boolean isAbstract();
boolean isFinal();
boolean isSynthetic();
boolean isStatic();
boolean isInterface();
boolean isSuper();
boolean isNative();
boolean isDeprecated();
boolean isSynchronized();
boolean isVolatile();
boolean isBridge();
boolean isVarargs();
boolean isTransient();
boolean isStrict();
boolean isAnnotation();
boolean isEnum();
int access();
/**
* This method is only a part of the contract to support deprecated methods.
* @param code
* @return
* @see DataClass#hasModifier(int)
* @see DataField#hasModifier(int)
* @see DataMethod#hasModifier(int)
*/
@Deprecated
boolean is(int code);
}
| 2,089 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
LocationRef.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/LocationRef.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* LocationRef
*
*
* @author Robert Field
*/
public abstract class LocationRef extends LocationAbstract {
LocationConcrete lc;
/**
* Creates a new instance of LocationAbstract
*/
LocationRef(int rootId, LocationConcrete lc) {
super(rootId);
this.lc = lc;
}
LocationRef(int rootId) {
this(rootId, (LocationConcrete) null);
}
public void setConcreteLocation(LocationConcrete lc) {
this.lc = lc;
}
public int startBCI() {
return lc.startBCI();
}
public int endBCI() {
return lc.endBCI();
}
LocationRef(int rootId, DataInput in) throws IOException {
super(rootId);
if (in.readBoolean()) {
int start = in.readShort();
int end = in.readShort();
final String kind = readString(in);
this.lc = new LocationConcrete(rootId, start, end) {
@Override
public String kind() {
return kind;
}
};
} else {
lc = null;
}
}
void writeObject(DataOutput out) throws IOException {
if (this.lc != null) {
out.writeBoolean(true);
out.writeShort(lc.startBCI());
out.writeShort(lc.endBCI());
writeString(out, kind());
} else {
out.writeBoolean(false);
}
}
} | 2,750 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Constants.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/Constants.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
/**
* Constants
*
* @author Robert Field
*/
public class Constants {
public static final String[] opcNames = {
"nop",
"aconst_null",
"iconst_m1",
"iconst_0",
"iconst_1",
"iconst_2",
"iconst_3",
"iconst_4",
"iconst_5",
"lconst_0",
"lconst_1",
"fconst_0",
"fconst_1",
"fconst_2",
"dconst_0",
"dconst_1",
"bipush",
"sipush",
"ldc",
"ldc_w",
"ldc2_w",
"iload",
"lload",
"fload",
"dload",
"aload",
"iload_0",
"iload_1",
"iload_2",
"iload_3",
"lload_0",
"lload_1",
"lload_2",
"lload_3",
"fload_0",
"fload_1",
"fload_2",
"fload_3",
"dload_0",
"dload_1",
"dload_2",
"dload_3",
"aload_0",
"aload_1",
"aload_2",
"aload_3",
"iaload",
"laload",
"faload",
"daload",
"aaload",
"baload",
"caload",
"saload",
"istore",
"lstore",
"fstore",
"dstore",
"astore",
"istore_0",
"istore_1",
"istore_2",
"istore_3",
"lstore_0",
"lstore_1",
"lstore_2",
"lstore_3",
"fstore_0",
"fstore_1",
"fstore_2",
"fstore_3",
"dstore_0",
"dstore_1",
"dstore_2",
"dstore_3",
"astore_0",
"astore_1",
"astore_2",
"astore_3",
"iastore",
"lastore",
"fastore",
"dastore",
"aastore",
"bastore",
"castore",
"sastore",
"pop",
"pop2",
"dup",
"dup_x1",
"dup_x2",
"dup2",
"dup2_x1",
"dup2_x2",
"swap",
"iadd",
"ladd",
"fadd",
"dadd",
"isub",
"lsub",
"fsub",
"dsub",
"imul",
"lmul",
"fmul",
"dmul",
"idiv",
"ldiv",
"fdiv",
"ddiv",
"irem",
"lrem",
"frem",
"drem",
"ineg",
"lneg",
"fneg",
"dneg",
"ishl",
"lshl",
"ishr",
"lshr",
"iushr",
"lushr",
"iand",
"land",
"ior",
"lor",
"ixor",
"lxor",
"iinc",
"i2l",
"i2f",
"i2d",
"l2i",
"l2f",
"l2d",
"f2i",
"f2l",
"f2d",
"d2i",
"d2l",
"d2f",
"i2b",
"i2c",
"i2s",
"lcmp",
"fcmpl",
"fcmpg",
"dcmpl",
"dcmpg",
"ifeq",
"ifne",
"iflt",
"ifge",
"ifgt",
"ifle",
"if_icmpeq",
"if_icmpne",
"if_icmplt",
"if_icmpge",
"if_icmpgt",
"if_icmple",
"if_acmpeq",
"if_acmpne",
"goto",
"jsr",
"ret",
"tableswitch",
"lookupswitch",
"ireturn",
"lreturn",
"freturn",
"dreturn",
"areturn",
"return",
"getstatic",
"putstatic",
"getfield",
"putfield",
"invokevirtual",
"invokespecial",
"invokestatic",
"invokeinterface",
"xxxunusedxxx",
"new",
"newarray",
"anewarray",
"arraylength",
"athrow",
"checkcast",
"instanceof",
"monitorenter",
"monitorexit",
"wide",
"multianewarray",
"ifnull",
"ifnonnull",
"goto_w",
"jsr_w",
"breakpoint"
};
public static int getOpCode(String opCode) {
for (int i = 0; i < opcNames.length; i++) {
if (opcNames[i].equals(opCode)) {
return i;
}
}
return -1;
}
}
| 5,313 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockTargetCase.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlockTargetCase.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
*
* @author Robert Field
*/
public class DataBlockTargetCase extends DataBlockTarget {
int targetValue;
/**
* Creates a new instance of DataBlockTargetCase
*/
public DataBlockTargetCase(int rootId, int value) {
super(rootId);
this.targetValue = value;
}
public DataBlockTargetCase(int rootId, int value, int slot, boolean attached, long count) {
super(rootId, slot, attached, count);
this.targetValue = value;
}
public boolean equals(Object o) {
return super.equals(o) && targetValue == ((DataBlockTargetCase) o).targetValue;
}
public int hashCode() {
return super.hashCode() + targetValue;
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.CASE;
}
void xmlAttrsValue(XmlContext cxt) {
cxt.attr(XmlNames.VALUE, targetValue);
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.writeInt(targetValue);
}
DataBlockTargetCase(int rootId, DataInput in) throws IOException {
super(rootId, in);
targetValue = in.readInt();
}
} | 2,506 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBranchCond.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBranchCond.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.IOException;
/**
* DataBranchCond
*
*
*
* @author Robert Field
*/
public class DataBranchCond extends DataBranch {
public DataBranchCond(int rootId, int bciFromStart, int bciFromEnd) {
super(rootId, bciFromStart, bciFromEnd);
}
DataBlockTarget branchTargetFallThrough() {
return getBranchTargets().get(1);
}
DataBlockTarget branchTargetJump() {
return getBranchTargets().get(0);
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.BRANCH;
}
DataBranchCond(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 1,930 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataMethodInvoked.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataMethodInvoked.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.data.Scale;
import com.sun.tdk.jcov.runtime.Collect;
import com.sun.tdk.jcov.runtime.CollectDetect;
import com.sun.tdk.jcov.tools.OneElemIterator;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
*
* @author Leonid Mesnik
*
* This class represents information about abstract and native methods. For
* static instrumentation, contains information about mapping whole method's
* signature to collector's slot (class Collect), which used in static
* instrumentation. This is done by invoking DataBlock's constructor, which
* grabs new slot from collector. This number is stored in jcov file then as
* method id (see getId() method) and used by StaticInvokeMethodAdapter later
* during ClassMorph2 work. For dynamic instrumentation method invocations are
* stored inside separate array (see CollectDetect), and jcov runtime knows
* mapping of signatures to slot indexes (see InvokeMethodAdapter). Instructions
* to hit CollectDetect are inserted by InvokeMethodAdapter later.
*
* To serve native methods in dynamic mode, another mechanism is used -
* mechanism of native wrappers.
*/
public class DataMethodInvoked extends DataMethod {
/**
* Method block information
*/
private final DataBlock entryBlock;
/**
* Creates a new instance of DataMethodInvoked
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
*/
public DataMethodInvoked(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
this(k, access, name, desc, signature, exceptions, -1);
}
/**
* Creates a new instance of DataMethodInvoked
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
* @param id
*/
public DataMethodInvoked(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions,
int id) {
super(k, access, name, desc, signature, exceptions, false);
boolean newSlot = (id == -1) ? true : false;
int slot = (newSlot) ? Collect.newSlot() : id;
entryBlock = new DataBlock(rootId, slot, newSlot, 0) {
@Override
public String kind() {
return "invoked"; //not used
}
@Override
protected boolean wasCollectHit() {
return CollectDetect.wasInvokeHit(DataAbstract.getInvokeID(k.getFullname(), name, desc));
}
@Override
protected long collectCount() {
return CollectDetect.invokeCountFor(DataAbstract.getInvokeID(k.getFullname(), name, desc));
}
@Override
protected void setCollectCount(long count) {
CollectDetect.setInvokeCountFor(DataAbstract.getInvokeID(k.getFullname(), name, desc), count);
}
@Override
protected void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.ID, getId());
ctx.attr(XmlNames.COUNT, getCount());
printScale(ctx);
}
};
LocationConcrete loc = new LocationConcrete(0) {
public String kind() {
return "trash";
}
};
entryBlock.setConcreteLocation(loc);
}
@Override
public DataMethod clone(DataClass newClass, int newAccess, String newName) {
return new DataMethodInvoked(newClass, newAccess, newName, this.getVmSignature(), this.getSignature(), this.getExceptions());
}
/**
* Get the ID of this method
*
* @return
*/
public int getId() {
return entryBlock.getId();
}
@Override
public boolean wasHit() {
return entryBlock.wasHit();
}
@Override
public long getCount() {
return entryBlock.getCount();
}
@Override
public void setCount(long cnt) {
entryBlock.setCount(cnt);
}
/**
* Set the scale information of this method
*
* @param s
*/
public void setScale(String s) {
entryBlock.readScale(s);
}
@Override
public Scale getScale() {
return entryBlock.scale;
}
@Override
public int getSlot() {
return entryBlock.slot;
}
@Override
public void xmlGen(XmlContext ctx) {
super.xmlGenBodiless(ctx);
}
@Override
void xmlAttrs(XmlContext ctx) {
super.xmlAttrs(ctx);
entryBlock.xmlAttrs(ctx);
}
@Override
public void checkCompatibility(DataMethod other, String trace) throws MergeException {
if (!(other instanceof DataMethodInvoked)) {
throw new MergeException("Method has other type than it's"
+ " merging copy, expected DataMethodInvoked; found " + other.getClass().getSimpleName(),
trace, MergeException.CRITICAL);
}
DataMethodInvoked m = (DataMethodInvoked) other;
if (!getDataRoot().getParams().isDynamicCollect() && !other.getDataRoot().getParams().isDynamicCollect()) {
if (getId() != m.getId()) {
throw new MergeException("Method has other id than it's"
+ " merging copy, expected " + getId() + "; found " + m.getId(),
trace, MergeException.CRITICAL);
}
}
}
@Override
public void merge(DataMethod other) {
DataMethodInvoked m = (DataMethodInvoked) other;
entryBlock.mergeScale(m.entryBlock);
entryBlock.setCount(getCount() + m.getCount());
}
public Iterator<DataBlock> iterator() {
return new OneElemIterator(entryBlock);
}
@Override
public List<DataBlock> getBlocks() {
ArrayList<DataBlock> list = new ArrayList<DataBlock>(1);
list.add(entryBlock);
return list;
}
@Override
public List<DataBranch> getBranches() {
return Collections.EMPTY_LIST;
}
@Override
public List<DataBlockTarget> getBranchTargets() {
return Collections.EMPTY_LIST;
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
entryBlock.writeObject(out);
}
DataMethodInvoked(final DataClass parent, DataInput in) throws IOException {
super(parent, in);
entryBlock = new DataBlock(rootId, in) {
@Override
public String kind() {
return "invoked"; //not used
}
@Override
protected boolean wasCollectHit() {
return CollectDetect.wasInvokeHit(DataAbstract.getInvokeID(parent.getFullname(), name, vmSig));
}
@Override
protected long collectCount() {
return CollectDetect.invokeCountFor(DataAbstract.getInvokeID(parent.getFullname(), name, vmSig));
}
@Override
protected void setCollectCount(long count) {
CollectDetect.setInvokeCountFor(DataAbstract.getInvokeID(parent.getFullname(), name, vmSig), count);
}
@Override
protected void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.ID, getId());
ctx.attr(XmlNames.COUNT, getCount());
printScale(ctx);
}
};
}
} | 9,000 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBranch.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBranch.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.io.PrintStream;
import java.util.Iterator;
/**
* <p> DataBranch class is abstract class representing branching classfile
* structures. DataBranchCond, DataBranchGoto and DataBranchSwitch extend this
* class. </p> <p> Each branch contain a number of blocks this branch is
* targeting. These blocks can be accessed by getBranchTargets() or
* getIterator(). </p>
*
* @author Robert Field
* @see DataBlockTarget
*/
public abstract class DataBranch extends DataExit {
public List<DataBlockTarget> branchTargets;
/**
* Creates a DataBranch object representing branch structure.
*
* @param rootId DataRoot id this branch belongs to
* @param bciStart start position of this block in classfile
* @param bciEnd end position of this block in classfile
*/
DataBranch(int rootId, int bciStart, int bciEnd) {
super(rootId, bciStart, bciEnd);
branchTargets = new ArrayList<DataBlockTarget>();
}
/**
* @return list of all targets this branch leads to
*/
public List<DataBlockTarget> getBranchTargets() {
return branchTargets;
}
/**
* Not supposed to be used outside
*
* @param target target to add
*/
public void addTarget(DataBlockTarget target) {
branchTargets.add(target);
target.setEnclosing(this);
}
void addBlocks(Collection<DataBlock> collection) {
for (DataBlock block : branchTargets) {
collection.add(block);
}
}
/**
* XML Generation
*/
@Override
void xmlBody(XmlContext ctx) {
// ctx.incIndent();
for (DataBlockTarget target : branchTargets) {
if (ctx.showBodiesInExitSubBlocks) { //Always
target.xmlGen(ctx);
} else {
target.xmlGenBodiless(ctx);
}
}
// ctx.decIndent();
}
/**
* @return iterator through all targets this branch leads to
*/
@Override
public Iterator<DataBlock> getIterator() {
return new Iterator<DataBlock>() {
private final Iterator<DataBlockTarget> delegate =
branchTargets.iterator();
public boolean hasNext() {
return delegate.hasNext();
}
public DataBlock next() {
return delegate.next();
}
public void remove() {
}
};
}
/**
* Debug printing
*/
@Override
void printDebug(PrintStream out, String indent) {
super.printDebug(out, indent);
String newIndent = indent + " ";
for (DataBlockTarget target : branchTargets) {
target.printDebug(out, newIndent);
}
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.writeShort(branchTargets.size());
for (DataBlockTarget t : branchTargets) {
if (t instanceof DataBlockTargetCase) {
out.write(1);
} else if (t instanceof DataBlockTargetCond) {
out.write(2);
} else if (t instanceof DataBlockTargetDefault) {
out.write(3);
} else if (t instanceof DataBlockTargetGoto) {
out.write(4);
} else {
throw new IOException("DataBranch.writeObject: Unknown dataBlockTarget class " + t.getClass().getName() + ".");
}
t.writeObject(out);
}
}
DataBranch(int rootId, DataInput in) throws IOException {
super(rootId, in);
int size = in.readShort();
branchTargets = new ArrayList<DataBlockTarget>(size);
for (int i = 0; i < size; ++i) {
byte code = in.readByte();
switch (code) {
case 1:
branchTargets.add(new DataBlockTargetCase(rootId, in));
break;
case 2:
branchTargets.add(new DataBlockTargetCond(rootId, in));
break;
case 3:
branchTargets.add(new DataBlockTargetDefault(rootId, in));
break;
case 4:
branchTargets.add(new DataBlockTargetGoto(rootId, in));
break;
default:
throw new IOException("DataBlockTarget with unknown code in DataBranch " + code);
}
}
}
} | 5,877 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockTargetDefault.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataBlockTargetDefault.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.IOException;
/**
* DataBlockTargetDefault
*
*
* @author Robert Field
*/
public class DataBlockTargetDefault extends DataBlockTarget {
/**
* Creates a new instance of DataBlockTargetDefault
*/
public DataBlockTargetDefault(int rootId) {
super(rootId);
}
public DataBlockTargetDefault(int rootId, int slot, boolean attached, long count) {
super(rootId, slot, attached, count);
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.DEFAULT;
}
DataBlockTargetDefault(int rootId, DataInput in) throws IOException {
super(rootId, in);
}
} | 1,936 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
LocationAbstract.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/LocationAbstract.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.PrintStream;
/**
*
*
* @author Robert Field
*/
public abstract class LocationAbstract extends DataAbstract implements Comparable<LocationAbstract> {
public LocationAbstract(int rootId) {
super(rootId);
}
public int compareTo(LocationAbstract loc) {
int comp = startBCI() - loc.startBCI();
if (comp == 0) {
// make sure non-equal don't return zero
comp = hashCode() - loc.hashCode();
}
return comp;
}
@Override
public String toString() {
return kind() + "(" + startBCI() + "," + endBCI() + ")@" + Integer.toHexString(hashCode());
}
abstract int startBCI();
abstract int endBCI();
/**
* XML Generation
*/
@Override
protected void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.START, startBCI());
ctx.attr(XmlNames.END, endBCI());
}
/**
* Debug printing
*/
void printDebug(PrintStream out, String indent) {
out.print(indent);
out.println(kind() + "(" + startBCI() + "," + endBCI() + ")");
}
}
| 2,354 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataMethodWithBlocks.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataMethodWithBlocks.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.data.Scale;
import com.sun.tdk.jcov.tools.DelegateIterator;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* DataMethodWithBlocks can contain any number of blocks inside of it.
*
* @author Robert Field
*/
public class DataMethodWithBlocks extends DataMethod {
/**
* Bytecode length
*/
private int bytecodeLength;
/**
*
*/
private CharacterRangeTable characterRangeTable = null;
/**
* Including blocks
*/
private BasicBlock[] basicBlocks;
/**
* Creates new instance of DataMethodWithBlocks
*
* @param k
* @param access
* @param name
* @param desc
* @param signature
* @param exceptions
*/
public DataMethodWithBlocks(final DataClass k,
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
super(k, access, name, desc, signature, exceptions, false);
}
@Override
public DataMethod clone(DataClass newClass, int newAccess, String newName) {
DataMethodWithBlocks dm = new DataMethodWithBlocks(newClass, newAccess, newName, this.getVmSignature(), this.getSignature(), this.getExceptions());
dm.setBasicBlocks(getBasicBlocks());
dm.setCharacterRangeTable(getCharacterRangeTable());
dm.setBytecodeLength(getBytecodeLength());
dm.lineTable = getLineTable();
return dm;
}
/**
* Set containing blocks
*
* @param basicBlocks
*/
public void setBasicBlocks(BasicBlock[] basicBlocks) {
this.basicBlocks = basicBlocks;
}
/**
* @return containing blocks
*/
public BasicBlock[] getBasicBlocks() {
return basicBlocks;
}
/**
* @return the bytecode length
*/
public int getBytecodeLength() {
return bytecodeLength;
}
/**
* Set bytecode length
*
* @param bytecodeLength
*/
public void setBytecodeLength(final int bytecodeLength) {
this.bytecodeLength = bytecodeLength;
}
/**
* Set CharacterRangeTable
*
* @param crt
*/
public void setCharacterRangeTable(CharacterRangeTable crt) {
this.characterRangeTable = crt;
}
/**
* Get CharacterRangeTable
*
* @return
*/
public CharacterRangeTable getCharacterRangeTable() {
return characterRangeTable;
}
@Override
public boolean hasCRT() {
return this.getCharacterRangeTable() != null;
}
@Override
public boolean wasHit() {
return getBasicBlocks() == null ? false : getBasicBlocks()[0].wasHit();
}
@Override
public long getCount() {
return getBasicBlocks() == null ? 0 : getBasicBlocks()[0].blocks().isEmpty() ? -1 : getBasicBlocks()[0].blocks().iterator().next().getCount();
}
@Override
public void setCount(long count) {
if (getBasicBlocks() != null && !getBasicBlocks()[0].blocks().isEmpty()) {
getBasicBlocks()[0].blocks().iterator().next().setCount(count);
}
}
@Override
public Scale getScale() {
return getBasicBlocks() == null ? null : getBasicBlocks()[0].blocks().isEmpty() ? null : getBasicBlocks()[0].blocks().iterator().next().scale;
}
@Override
public int getSlot() {
return getBasicBlocks() == null ? -1 : getBasicBlocks()[0].blocks().isEmpty() ? -1 : getBasicBlocks()[0].blocks().iterator().next().slot;
}
@Override
void xmlAttrs(XmlContext ctx) {
super.xmlAttrs(ctx);
ctx.attr(XmlNames.LENGTH, getBytecodeLength());
}
@Override
void xmlBody(XmlContext ctx) {
if (getBasicBlocks() != null) {
for (BasicBlock bb : getBasicBlocks()) {
bb.xmlGen(ctx);
}
}
if (ctx.showLineTable && getLineTable() != null) {
xmlLineTable(ctx);
}
if (ctx.showRangeTable && getCharacterRangeTable() != null) {
getCharacterRangeTable().xmlGen(ctx);
}
}
@Override
public void checkCompatibility(DataMethod other, String trace) throws MergeException {
if (!(other instanceof DataMethodWithBlocks)) {
throw new MergeException("Method has other type than it's"
+ " merging copy, expected DataMethodWithBlocks; found " + other.getClass().getSimpleName(),
trace, MergeException.CRITICAL);
}
DataMethodWithBlocks m = (DataMethodWithBlocks) other;
if (getBasicBlocks().length != m.getBasicBlocks().length) {
throw new MergeException("Method has other number of basic blocks than "
+ "it's merging copy, the number is " + getBasicBlocks().length,
trace, MergeException.CRITICAL);
}
for (BasicBlock bb : getBasicBlocks()) {
for (BasicBlock bbo : m.getBasicBlocks()) {
if (bb.startBCI() == bbo.startBCI() || bb.endBCI() == bbo.endBCI()) {
if (bb.startBCI() == bbo.startBCI() && bb.endBCI() == bbo.endBCI()) {
try {
bb.checkCompatibility(bbo);
} catch (MergeException e) {
e.location = trace + ", block " + bb.startBCI() + "-" + bb.endBCI() + e.location;
throw e;
}
break;
} else {
System.err.println("* WARNING *: block ranges are invalid in " + trace + ": [" + bbo.startBCI() + "; " + bbo.endBCI() + "] (expected [" + bb.startBCI() + "; " + bb.endBCI() + "]). This can mean that you are merging results from different product versions.");
}
}
}
}
}
@Override
public void merge(DataMethod other) {
DataMethodWithBlocks m = (DataMethodWithBlocks) other;
for (BasicBlock bb : getBasicBlocks()) {
for (BasicBlock bbo : m.getBasicBlocks()) {
if (bb.startBCI() == bbo.startBCI()
&& bb.endBCI() == bbo.endBCI()) {
bb.merge(bbo);
break;
}
}
}
}
/**
* Debug printing
*/
void printDebug(PrintStream out, String indent) {
out.print(indent);
out.println("Method: " + getName());
String newIndent = indent + " ";
for (BasicBlock bb : getBasicBlocks()) {
bb.printDebug(out, newIndent);
}
}
public Iterator<DataBlock> iterator() {
return new DelegateIterator<DataBlock>() {
private int i;
@Override
protected Iterator<DataBlock> nextIterator() {
if (i < getBasicBlocks().length) {
return getBasicBlocks()[i++].getIterator();
} else {
return null;
}
}
};
}
@Override
public List<DataBlock> getBlocks() {
LinkedList<DataBlock> blocks = new LinkedList<DataBlock>();
for (BasicBlock bb : basicBlocks) {
for (DataBlock db : bb.blocks()) {
// if (!(db instanceof DataBlockTarget))
blocks.add(db);
}
}
return blocks;
}
@Override
public List<DataBranch> getBranches() {
LinkedList<DataBranch> branches = new LinkedList<DataBranch>();
for (BasicBlock bb : basicBlocks) {
if (bb.exit instanceof DataBranch) {
branches.add((DataBranch) bb.exit);
}
}
return branches;
}
@Override
public List<DataBlockTarget> getBranchTargets() {
LinkedList<DataBlockTarget> targets = new LinkedList<DataBlockTarget>();
for (BasicBlock bb : basicBlocks) {
if (bb.exit instanceof DataBranch) {
DataBranch br = (DataBranch) bb.exit;
for (DataBlockTarget db : br.branchTargets) {
targets.add(db);
}
}
}
return targets;
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.writeShort(bytecodeLength);
// characterRangeTable
out.writeShort(basicBlocks.length);
for (int i = 0; i < basicBlocks.length; ++i) {
if (basicBlocks[i] instanceof SimpleBasicBlock) {
out.write(1);
} else {
out.write(2);
}
basicBlocks[i].writeObject(out);
}
}
DataMethodWithBlocks(DataClass parent, DataInput in) throws IOException {
super(parent, in);
bytecodeLength = in.readShort();
// charRangeTable
int bblen = in.readShort();
basicBlocks = new BasicBlock[bblen];
for (int i = 0; i < bblen; ++i) {
byte code = in.readByte();
switch (code) {
case 1:
basicBlocks[i] = new SimpleBasicBlock(rootId, in);
break;
case 2:
basicBlocks[i] = new BasicBlock(rootId, in);
break;
default:
throw new IOException("BasicBlock with unknown code in DataMethodWithBlocks " + code);
}
}
}
} | 10,880 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
MergeException.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/MergeException.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
/**
* @author Dmitry Fazunenko
* @author Sergey Borodin
*/
public class MergeException extends Exception {
String descr;
String location;
/**
* How ctritical the situation:
*/
int severity = 0;
public static final int CRITICAL = 0;
public static final int HIGH = 1;
public static final int MEDIUM = 2;
public static final int LOW = 3;
MergeException() {
}
MergeException(String descr, String location, int severity) {
this.descr = descr;
this.location = location;
checkSeverity(severity);
this.severity = severity;
}
@Override
public String getMessage() {
return "Merge exception: " + descr + "\n"
+ "Exception occurred in: " + location;
}
public void setSeverity(int severity) {
checkSeverity(severity);
this.severity = severity;
}
public int getSeverity() {
return severity;
}
private void checkSeverity(int sev) {
if (sev < CRITICAL || sev > LOW) {
throw new IllegalArgumentException("Internal error: Illegal severity value " + sev);
}
}
}
| 2,401 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
XmlContext.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/XmlContext.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.instrument.InstrumentationOptions.InstrumentationMode;
import java.io.BufferedOutputStream;
import java.util.Stack;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* XmlContext
*
*
* @author Robert Field
*/
public class XmlContext extends PrintWriter {
final String indentDelta;
String indent;
Stack<String> indentHistory;
boolean showAbstract = true;
boolean showNonNested = true;
boolean showBodiesInExitSubBlocks = true;
boolean showBasicBlocks = false;
boolean showDetailBlocks = true;
boolean showLineTable = true;
boolean showRangeTable = true;
InstrumentationParams params;
boolean skipNotCoveredClasses = false;
/**
* Creates a new instance of XmlContext
*/
public XmlContext(String filename, InstrumentationParams params) throws FileNotFoundException {
super(new BufferedOutputStream(new FileOutputStream(filename)));
indent = "";
indentDelta = "\t";
indentHistory = new Stack<String>();
configureContext(params);
}
public XmlContext(OutputStream out, InstrumentationParams params) throws FileNotFoundException {
super(out);
indent = "";
indentDelta = "\t";
indentHistory = new Stack<String>();
configureContext(params);
}
// Debug needs (flushing to System.output)
public XmlContext() throws FileNotFoundException {
super(System.out);
indent = "";
indentDelta = "\t";
indentHistory = new Stack<String>();
}
public XmlContext(OutputStream out) throws FileNotFoundException {
super(out);
indent = "";
indentDelta = "\t";
indentHistory = new Stack<String>();
}
public void configureContext(InstrumentationMode mode, boolean showAbstract) {
if (mode.equals(InstrumentationMode.BLOCK)) {
showNonNested = false;
showBasicBlocks = true;
showDetailBlocks = false;
}
this.showAbstract = showAbstract;
}
public void incIndent() {
indentHistory.push(indent);
indent += indentDelta;
}
public void decIndent() {
indent = indentHistory.pop();
}
public void indent() {
print(indent);
}
public void indentPrintln(String str) {
indent();
println(str);
}
public void attr(String name, String value) {
print(" " + name + "=\"");
writeEscaped(value);
print("\"");
}
public void attr(String name, Object value) {
print(" " + name + "=\"");
writeEscaped(value.toString());
print("\"");
}
public void attr(String name, int value) {
print(" " + name + "=\"" + value + "\"");
}
public void attr(String name, long value) {
print(" " + name + "=\"" + value + "\"");
}
public void attr(String name, boolean value) {
print(" " + name + "=\"" + value + "\"");
}
public void attrNormalized(String name, String value) {
print(" " + name + "=\"");
writeEscaped(value);
print("\"");
}
public final void configureContext(InstrumentationParams params) {
this.params = params;
if (params.getMode().equals(InstrumentationMode.BLOCK)) {
showNonNested = false;
showBasicBlocks = true;
showDetailBlocks = false;
}
this.showAbstract = params.isInstrumentAbstract();
}
public void setSkipNotCoveredClasses(boolean skipNotCoveredClasses) {
this.skipNotCoveredClasses = skipNotCoveredClasses;
}
public void writeEscaped(String str) {
if (str == null){
return;
}
for (int i = 0, j = str.length(); i < j; i++) {
int ch = str.charAt(i);
switch (ch) {
case '&':
write("&");
break;
case '<':
write("<");
break;
case '>':
write(">");
break;
case '\'':
write("'");
break;
case '"':
write(""");
break;
default:
write(ch);
}
}
}
}
| 5,718 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataClass.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataClass.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.instrument.asm.ASMModifiers;
import com.sun.tdk.jcov.util.NaturalComparator;
import com.sun.tdk.jcov.filter.MemberFilter;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* DataClass contains information about one class. Can include methods and
* fields.
*
*
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*
* @see DataClass#methods
* @see DataClass#fields
* @see DataMethod
* @see DataField
* @see DataPackage
*/
public class DataClass extends DataAnnotated implements Comparable<DataClass> {
/**
* Full (VM) name of associated class
*/
private final String fullname;
/**
* Module name of associated class
*/
private String moduleName;
/**
* Short name of associated class
*/
private final String name;
/**
* Optional checksum
*/
private long checksum;
/**
* All methods registered in this class
*/
private final List<DataMethod> methods;
/**
* All fields registered in this class
*/
private final List<DataField> fields;
/**
* Container for access code of this class
*/
private Modifiers access;
/**
* Class signature
*/
private String signature;
/**
* Superclass full (VM) name (or java/lang/Object)
*/
private String superName;
/**
* Associated source file
*/
private String source;
/**
* Implementing interfaces divided with ';'. Can be null
*/
private String superInterfaces;
/**
* Check whether this DataClass is configured to differ elements - classes
* vs interfaces False always
*/
private final boolean differentiateClass;
private static final Logger logger;
static {
logger = Logger.getLogger(DataClass.class.getName());
}
private boolean inner = false;
private boolean anonym = false;
/**
* Creates a new instance of DataClass. Use setInfo method to set up
* additional data<br/><br/>
*
* Use setInfo to set up additional parameters
*
* @see #setInfo
* @param rootId
* @param fullname can't be null
* @param checksum
* @param differentiateClass
*/
public DataClass(int rootId, String fullname, String moduleName, long checksum, boolean differentiateClass) {
super(rootId);
this.fullname = fullname;
this.checksum = checksum;
int slash = fullname.lastIndexOf('/');
if (slash < 0) {
this.name = fullname;
} else {
this.name = fullname.substring(slash + 1);
}
this.methods = new LinkedList<DataMethod>();
this.fields = new LinkedList<DataField>();
this.differentiateClass = differentiateClass; // is always false at the moment
this.moduleName = moduleName;
}
public String getModuleName(){
return moduleName;
}
public void setModuleName(String moduleName){
this.moduleName = moduleName;
}
/**
* Set up additional data
*
* @param flags
* @param signature
* @param superName
* @param interfaces
*/
public void setInfo(String flags, String signature, String superName, String interfaces) {
String[] accessFlags = flags.split(" ");
String[] sInterfaces = null;
if (interfaces != null) {
sInterfaces = interfaces.split(";");
}
setInfo(access(accessFlags), signature, superName, sInterfaces);
}
/**
* Set up additional data
*
* @param access
* @param signature
* @param superName
* @param interfaces
*/
public void setInfo(Modifiers access, String signature, String superName, String[] interfaces) {
this.access = access;
this.signature = signature;
this.superName = superName;
if (interfaces != null && interfaces.length > 0) {
this.superInterfaces = interfaces[0];
for (int i = 1; i < interfaces.length; i++) {
this.superInterfaces += ";" + interfaces[i];
}
}
}
@Override
public boolean equals(Object o) {
if (!(o instanceof DataClass)) {
return false;
}
DataClass clazz = (DataClass) o;
boolean eq = fullname.equals(clazz.fullname);
if (checksum != -1 && clazz.checksum != -1) {
eq = eq && (checksum == clazz.checksum);
}
return eq;
}
@Override
public int hashCode() {
int hash = 7;
hash = 17 * hash + (fullname != null ? fullname.hashCode() : 0);
// hash = 17 * hash + (int)checksum;
return hash;
}
/**
* Set source file associated with this DataClass
*
* @param source
*/
public void setSource(String source) {
this.source = source;
}
/**
* Get source file associated with this DataClass
*
* @return source file associated with this DataClass
*/
public String getSource() {
return source;
}
/**
* Set superclass fullname (VM)
*
* @param superName
*/
public void setSuperName(String superName) {
this.superName = superName;
}
/**
* Get superclass fullname (VM)
*
* @return superclass fullname (VM)
*/
public String getSuperName() {
return superName;
}
/**
* Set the signature of this class
*
* @param signature
*/
public void setSignature(String signature) {
this.signature = signature;
}
/**
* Get the signature of this class
*
* @return the signature of this class
*/
public String getSignature() {
return signature;
}
/**
* Set access code of this class
*
* @param access
*/
public void setAccess(int access) {
this.access = new ASMModifiers(access);
}
/**
* Get access code of this class
*
* @return access code of this class
*/
public int getAccess() {
return access.access();
}
public Modifiers getModifiers() { return access; }
/**
* Set checksum of this class. It's used in equals() method
*
* @param checksum
*/
public void setChecksum(long checksum) {
this.checksum = checksum;
}
/**
* Get checksum of this class. It's used in equals() method
*
* @return checksum of this class. It's used in equals() method
*/
public long getChecksum() {
return checksum;
}
/**
* Set interfaces this class is implementing (divided with ';' or null if no
* one)
*
* @param superInterfaces
*/
public void setSuperInterfaces(String superInterfaces) {
this.superInterfaces = superInterfaces;
}
/**
* Get interfaces this class is implementing (divided with ';' or null if no
* one)
*
* @return interfaces this class is implementing (divided with ';' or null
* if no one)
*/
public String getSuperInterfaces() {
return superInterfaces;
}
/**
* Get simple class name
*
* @return simple class name
*/
public String getName() {
return name;
}
/**
* Get full (VM) class name
*
* @return full (VM) class name
*/
public String getFullname() {
return fullname;
}
/**
* Detects package from the full (VM) classname
*
* @return package from the full (VM) classname
*/
public String getPackageName() {
int slash = fullname.lastIndexOf('/');
if (slash < 0) {
return "";
} else {
return fullname.substring(0, slash);
}
}
/**
* Get this class`s access flags as String array
*
* @return this class`s access flags as String array
*/
public String[] getAccessFlags() {
return accessFlags(access);
}
/**
* Check whether <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*
* @see #getAccess()
* @return true if <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*/
@Deprecated
public boolean isPublic() { return isPublicAPI(); }
/**
* Check whether <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*
* @see #getAccess()
* @return true if <b>access</b> field has ACC_PUBLIC or ACC_PROTECTED flag
*/
public boolean isPublicAPI() {
return access.isPublic() || access.isProtected();
}
/**
* Checks whether this class has 'private' modifier
*
* @return true if class is private
*/
@Deprecated
public boolean hasPrivateModifier() {
return access.isPrivate();
}
/**
* Checks whether this class has 'public ' modifier
*
* @return true if class is public
*/
@Deprecated
public boolean hasPublicModifier() {
return access.isPublic();
}
/**
* Checks whether this class has 'protected' modifier
*
* @return true if class is protected
*/
@Deprecated
public boolean hasProtectedModifier() {
return access.isProtected();
}
/**
* Checks whether this class has 'abstract' modifier
*
* @return true if class is abstract
*/
@Deprecated
public boolean hasAbstractModifier() {
return access.isAbstract();
}
/**
* Checks whether this class has 'static' modifier
*
* @return true if class is static
*/
@Deprecated
public boolean hasStaticModifier() {
return access.isStatic();
}
/**
* Checks whether this class has specified modifier
*
* @return true if class has specified modifier
* @see DataClass#getAccess()
*/
@Deprecated
public boolean hasModifier(int modifierCode) { return access.is(modifierCode); }
/**
* Add method data to this class
*
* @see DataMethod
* @param method
*/
public void addMethod(DataMethod method) {
methods.add(method);
}
/**
* Finds method info in this class
*
* @param methname
* @return method or null if not found
*/
public DataMethod findMethod(String methname) {
if (methname == null) {
return null;
}
for (DataMethod dm : methods) {
if (dm.getName().equals(methname)) {
return dm;
}
}
return null;
}
/**
* Removes method info from this class
*
* @param methname
* @return removed method or null if not found
*/
public DataMethod removeMethod(String methname) {
if (methname == null) {
return null;
}
Iterator<DataMethod> it = methods.iterator();
while (it.hasNext()) {
DataMethod dm = it.next();
if (dm.getName().equals(methname)) {
it.remove();
return dm;
}
}
return null;
}
/**
* Add field data to this class
*
* @see DataField
* @param field
*/
public void addField(DataField field) {
fields.add(field);
}
/**
* Find field info in this class
*
* @param fieldname
* @return field or null if not found
*/
public DataField findField(String fieldname) {
if (fieldname == null) {
return null;
}
for (DataField df : fields) {
if (df.getName().equals(fieldname)) {
return df;
}
}
return null;
}
/**
* Removes field info from this class
*
* @param fieldname
* @return removed field or null if not found
*/
public DataField removeField(String fieldname) {
if (fieldname == null) {
return null;
}
Iterator<DataField> it = fields.iterator();
while (it.hasNext()) {
DataField dm = it.next();
if (dm.getName().equals(fieldname)) {
it.remove();
return dm;
}
}
return null;
}
/**
* Get list of all methods associated with this class
*
* @see DataMethod
* @return list of all methods associated with this class
*/
public List<DataMethod> getMethods() {
return methods;
}
/**
* Get list of all fields associated with this class
*
* @see DataField
* @return list of all fields associated with this class
*/
public List<DataField> getFields() {
return fields;
}
/**
* Check whether this class was hit. Checks one-by-one all methods and all
* fields in this class. Class is hit only is any method or field is hit.
*
* @return true if this class was hit
*/
public boolean wasHit() {
for (DataMethod method : methods) {
if (method.wasHit()) {
return true;
}
}
for (DataField field : fields) {
if (field.wasHit()) {
return true;
}
}
return false;
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
public String kind() {
if (differentiateClass) {
return access.isInterface() ? XmlNames.INTERFACE : XmlNames.CLASS;
} else {
return XmlNames.CLASS;
}
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
public void xmlGen(XmlContext ctx) {
if ((!ctx.skipNotCoveredClasses || wasHit() && methods.size() > 0)) {
// check abstract on
if (ctx.showAbstract) {
super.xmlGen(ctx);
} else if (!access.isInterface()) {
super.xmlGen(ctx);
} else {
// cheking interface
// find default methods even when abstract off
List<DataMethod> onlyDefaultMethods = new ArrayList<DataMethod>();
for (DataMethod method : methods) {
if (!method.getModifiers().isAbstract()) {
onlyDefaultMethods.add(method);
}
}
this.methods.retainAll(onlyDefaultMethods);
if (methods.size() > 0) {
super.xmlGen(ctx);
}
}
}
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
void xmlAttrs(XmlContext ctx) {
ctx.attr(XmlNames.NAME, name);
ctx.attr(XmlNames.SUPERNAME, superName == null ? "" : superName);
if (checksum != -1) {
ctx.attr(XmlNames.CHECKSUM, checksum);
}
if (!differentiateClass && !access.isInterface()) {
ctx.attr(XmlNames.INTERFACE, true);
}
if (signature != null) {
ctx.attrNormalized(XmlNames.SIGNATURE, signature);
}
if (source != null) {
ctx.attrNormalized(XmlNames.SOURCE, source);
}
if (inner) {
if (anonym) {
ctx.attr(XmlNames.INNER_CLASS, "anon");
} else {
ctx.attr(XmlNames.INNER_CLASS, "inner");
}
}
xmlAccessFlags(ctx, access);
super.xmlAttrs(ctx);
}
/**
* XML Generation. Not supposed to use outside.
*/
@Override
void xmlBody(XmlContext ctx) {
// Collections.sort(methods);
for (DataMethod method : methods) {
method.xmlGen(ctx);
}
// Collections.sort(fields);
for (DataField field : fields) {
field.xmlGen(ctx);
}
}
/**
* Decode class`s access flags as String array
*
* @param access
* @return class`s access flags as String array
*/
@Override
String[] accessFlags(Modifiers access) {
String[] as = super.accessFlags(access);
List<String> lst = new LinkedList();
for (String s : as) {
if (!XmlNames.A_SYNCHRONIZED.equals(s)) {
lst.add(s);
}
}
return lst.toArray(new String[lst.size()]);
}
/**
* Cloneable interface
*
* @param rootId
* @return clone
*/
public DataClass clone(int rootId) {
DataClass res = new DataClass(rootId, fullname, moduleName, -1, differentiateClass);
res.access = access;
res.signature = signature;
res.superName = superName;
res.superInterfaces = superInterfaces;
res.source = source;
res.methods.addAll(methods);
res.fields.addAll(fields);
return res;
}
@Override
public int compareTo(DataClass clz) {
return NaturalComparator.INSTANCE.compare(this.name, clz.getName());
}
/**
* Checks whether this class is compatible with <b>other</b>
*
* @param other
* @param traceString
* @param severity a level of error ignorance
* @param boe true means that checkCompatibility will stop on the first
* occurred critical (see <b>severity</b>) error
* @return Number of errors (if <b>boe</b> is set to true it can be only 1)
* @throws MergeException
*/
public int checkCompatibility(DataClass other, String traceString, int severity, boolean boe) throws MergeException {
int errors = 0;
try {
checkEquals(other, traceString + ": " + other.fullname);
} catch (MergeException me) {
if (isCritical(me, severity)) {
throw me;
} else {
logger.log(Level.INFO, me.getMessage());
}
}
for (DataMethod meth : methods) {
for (DataMethod ometh : other.methods) {
if (meth.equals(ometh)) {
try {
meth.checkCompatibility(ometh, traceString + ": " + other.fullname + "." + ometh.getName() + ometh.getVmSignature());
} catch (MergeException e) {
if (isCritical(e, severity)) {
errors++;
logger.log(Level.SEVERE, "Error while merging method " + ometh.getName() + ometh.getVmSignature(), e);
if (boe) {
return errors;
}
} else {
logger.log(Level.WARNING, "Error while merging method " + ometh.getName() + ometh.getVmSignature() + " - skipped as not critical", e);
}
}
break;
}
}
}
for (DataField fld : fields) {
for (DataField ofld : other.fields) {
if (fld.equals(ofld)) {
try {
fld.checkCompatibility(ofld, traceString + ": " + other.fullname + "." + ofld.getName());
} catch (MergeException e) {
if (isCritical(e, severity)) {
errors++;
logger.log(Level.SEVERE, "Error while merging field " + ofld.getName(), e);
if (boe) {
return errors;
}
} else {
logger.log(Level.WARNING, "Error while merging field " + ofld.getName() + " - skipped as not critical", e);
}
}
break;
}
}
}
return errors;
}
public void mergeSorted(DataClass other) {
ListIterator<? extends Comparable> thisIt = methods.listIterator();
ListIterator<? extends Comparable> otherIt = other.methods.listIterator();
Comparable thisC = null, otherC = null;
if (!thisIt.hasNext()) {
// should not happen - at least init() should exist
} else {
while (otherIt.hasNext()) {
otherC = otherIt.next();
thisC = thisIt.next();
int comp = thisC.compareTo(otherC);
while (thisIt.hasNext() && comp < 0) {
thisC = thisIt.next();
comp = thisC.compareTo(otherC);
}
if (comp == 0) {
// found - merging class
((DataMethod) thisC).merge((DataMethod) otherC);
} else if (comp > 0) {
// no such class in thisClasses
} else {
// comp < 0 - thisClasses has no more elements - all that left are missing in thisClasses
break; // need to break as next iteration will call next() which will fail
}
}
}
thisIt = fields.listIterator();
otherIt = other.fields.listIterator();
thisC = null;
otherC = null;
if (!thisIt.hasNext()) {
} else {
while (otherIt.hasNext()) {
otherC = otherIt.next();
thisC = thisIt.next();
int comp = thisC.compareTo(otherC);
while (thisIt.hasNext() && comp < 0) {
thisC = thisIt.next();
comp = thisC.compareTo(otherC);
}
if (comp == 0) {
// found - merging class
((DataField) thisC).merge((DataField) otherC);
} else if (comp > 0) {
// no such class in thisClasses
} else {
// comp < 0 - thisClasses has no more elements - all that left are missing in thisClasses
break; // need to break as next iteration will call next() which will fail
}
}
}
if (checksum == -1) {
checksum = other.checksum;
}
}
/**
* Merges information from <b>other</b> to this DataClass. <br/><br/>
*
* This only sums hit count and scales - any difference in class structure
* is an error
*
* @param other
*/
public void merge(DataClass other) {
for (DataMethod meth : methods) {
for (DataMethod ometh : other.methods) {
if (meth.equals(ometh)) {
meth.merge(ometh);
break;
} // XXX meth not found
}
}
for (DataField fld : fields) {
for (DataField ofld : other.fields) {
if (fld.equals(ofld)) {
fld.merge(ofld);
break;
} // XXX field not found
}
}
if (checksum == -1) {
checksum = other.checksum;
}
}
/**
* Merge class data with another one without looking into blocks structure
*
* @param otherClass
*/
public void mergeOnSignatures(DataClass otherClass) {
ListIterator<DataMethod> other_it = otherClass.methods.listIterator();
outer:
while (other_it.hasNext()) {
DataMethod otherMethod = other_it.next();
ListIterator<DataMethod> it = methods.listIterator();
while (it.hasNext()) {
DataMethod thisMethod = it.next();
if (otherMethod.getFullName().equals(thisMethod.getFullName())) { // signature checking only
if (otherMethod instanceof DataMethodEntryOnly) {
thisMethod.merge(otherMethod);
} else {
// it's terrible but better than creating new DataMethodEntryOnly from otherMethod
thisMethod.iterator().next().mergeScale(otherMethod.iterator().next());
thisMethod.setCount(thisMethod.getCount() + otherMethod.getCount());
}
continue outer;
}
}
// means that this method is missing - it's an error, but ignoring - just writting warning
System.out.println("Warning, class " + otherClass.getFullname() + " has method " + otherMethod.name + " that was not found in template");
}
// fields
outer:
for (DataField otherFields : otherClass.fields) {
ListIterator<DataField> it = fields.listIterator();
while (it.hasNext()) {
DataField thisField = it.next();
if (otherFields.equals(thisField)) { // parent && signature checking only
thisField.merge(otherFields);
continue outer;
}
}
// means that this field is missing - it's an error, but ignoring - just writting warning
System.out.println("Warning, class " + otherClass.getFullname() + " has field " + otherFields.getName() + " that was not found in template");
}
}
/**
* Return true, if merge error is critical, false for warnings
*
* @param level - loose level set by user
* @return true, if merge error is critical, false for warnings
*/
private static boolean isCritical(MergeException me, int level) {
int errorSeverity = me.getSeverity();
if (level == 0 || errorSeverity == 0) {
return true;
}
if (level == 1 && errorSeverity == 3) {
return false;
}
if (level == 2 && errorSeverity >= 2) {
return false;
}
if (level == 3) {
return false;
}
return true;
}
/**
* Check that this method and another one are identical. <br/><br/>
*
* Name mismatch is a critical one (can't be skipped - different classes
* compared). <br/> Checksum or methods size mismatch is high priority
* error.<br/> Signature, access and field size mismatch is low priority
* error.
*
* @param other
* @param trace
* @throws MergeException with severity level set
*/
private void checkEquals(DataClass other, String trace) throws MergeException {
if (!fullname.equals(other.fullname)) {
throw new MergeException(
"Fullname mismatch: expected '" + fullname + "'; found '" + other.fullname + "'",
trace, MergeException.CRITICAL);
}
if (checksum != -1 && other.checksum != -1 && checksum != other.checksum) {
throw new MergeException(
"Checksum mismatch: expected '" + checksum + "'; found '" + other.checksum + "'",
trace, MergeException.HIGH);
}
if (methods.size() != other.methods.size()) {
throw new MergeException(
"Method size mismatch: expected '" + methods.size() + "'; found '" + other.methods.size() + "'",
trace, MergeException.HIGH);
}
if (signature != null && !signature.equals(other.signature)) {
throw new MergeException(
"Signature mismatch: expected '" + signature + "'; found '" + other.signature + "'",
trace, MergeException.MEDIUM);
}
// if any problems with access - make mask to filter out access codes in DataClass(int, DataInput)
if (access.isSuper() != other.access.isSuper()) {
throw new MergeException(
"Access mismatch: expected '" + access.access() + "'; found '" + other.access.access() + "'",
trace, MergeException.LOW);
}
if (fields.size() != other.fields.size()) {
throw new MergeException(
"Field size mismatch: expected '" + fields.size() + "'; found '" + other.fields.size() + "'",
trace, MergeException.LOW);
}
}
/**
* Root scale_size should be expanded before invoking this
*
* @param add_before
*/
void expandScales(int newSize, boolean add_before) {
for (DataMethod m : methods) {
for (DataBlock bl : m) {
bl.expandScales(newSize, add_before);
}
}
for (DataField fld : fields) {
for (DataBlock bl : fld) {
bl.expandScales(newSize, add_before);
}
}
}
/**
* Root scale_size should be expanded before invoking this
*
* @param add_before
*/
void expandScales(int newSize, boolean add_before, int newcount) {
for (DataMethod m : methods) {
for (DataBlock bl : m) {
bl.expandScales(newSize, add_before, newcount);
}
}
for (DataField fld : fields) {
for (DataBlock bl : fld) {
bl.expandScales(newSize, add_before, newcount);
}
}
}
/**
* Removes members rejected by the filter from this class.
*
* @param filter
*/
public void applyFilter(MemberFilter filter) {
Iterator it = methods.iterator();
while (it.hasNext()) {
DataMethod next = (DataMethod) it.next();
if (!filter.accept(this, next)) {
it.remove();
}
}
it = fields.iterator();
while (it.hasNext()) {
DataField next = (DataField) it.next();
if (!filter.accept(this, next)) {
it.remove();
}
}
}
/**
* Sort out fields and methods in this class
*/
public void sort() {
Collections.sort(methods);
Collections.sort(fields);
}
void writeObject(DataOutput out) throws IOException {
super.writeObject(out);
out.writeUTF(name);
writeString(out, moduleName);
writeString(out, fullname);
writeString(out, signature);
writeString(out, source);
writeString(out, superName);
writeString(out, superInterfaces);
out.writeLong(checksum);
out.writeInt(access.access());
out.writeByte((differentiateClass ? 1 : 0) + (inner ? 2 : 0) + (anonym ? 4 : 0));
out.writeShort(fields.size());
for (DataField f : fields) {
f.writeObject(out);
}
out.writeShort(methods.size());
for (DataMethod m : methods) {
if (m instanceof DataMethodEntryOnly) {
if (m.access.isNative() || m.access.isAbstract()) {
out.write(2); // DMI
} else {
out.write(1); // DMEO
}
} else if (m instanceof DataMethodInvoked) {
if (m.access.isNative() || m.access.isAbstract()) {
out.write(2); // DMI
} else {
out.write(1); // DMEO
}
} else if (m instanceof DataMethodWithBlocks) {
out.write(3);
} else {
System.out.println("ERROR " + m.getFullName());
out.write(4);
throw new IOException("DataClass.writeObject - Unknown dataMethod class " + m.getClass().getName() + ".");
}
m.writeObject(out);
}
}
DataClass(int rootID, DataInput in) throws IOException {
super(rootID, in);
//moduleName = "test.java.base";
name = in.readUTF();
moduleName = readString(in);
fullname = readString(in);
signature = readString(in);
source = readString(in);
superName = readString(in);
superInterfaces = readString(in);
checksum = in.readLong();
access = new ASMModifiers(in.readInt());
byte b = in.readByte();
differentiateClass = (b & 1) != 0;
inner = (b & 2) != 0;
anonym = (b & 4) != 0;
int fieldsNum = in.readShort();
fields = new ArrayList<DataField>(fieldsNum);
for (int i = 0; i < fieldsNum; ++i) {
fields.add(new DataField(this, in));
}
int methodsNum = in.readShort();
methods = new ArrayList<DataMethod>(methodsNum);
for (int i = 0; i < methodsNum; ++i) {
byte code = in.readByte();
switch (code) {
case 1:
methods.add(new DataMethodEntryOnly(this, in));
break;
case 2:
methods.add(new DataMethodInvoked(this, in));
break;
case 3:
methods.add(new DataMethodWithBlocks(this, in));
break;
default:
throw new IOException("DataMethod with unknown code in DataClass " + code);
}
}
}
public void setInner(boolean inner) {
this.inner = inner;
}
public boolean isInner() {
return inner;
}
public boolean isAnonymous() {
return anonym;
}
public void setAnonym(boolean b) {
this.anonym = b;
}
} | 34,731 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
InstrumentationPlugin.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/InstrumentationPlugin.java | package com.sun.tdk.jcov.instrument;
import java.nio.file.Path;
public interface InstrumentationPlugin {
/**
* Called after all instrumentation is complete.
*
* @throws Exception should some
*/
void instrumentationComplete() throws Exception;
/**
* For the instrumented code to work independently (i.e. without adding additional classes to the classpath), some
* classes can be "implanted" into the instrumented code.
*
* @return Path containing the classes to be implanted. Must be in a form which can be added to Java classpath.
*/
//TODO perhaps this can return a list of classes to be implanted
Path runtime() throws Exception;
/**
* Name of a package which contains code, that will be called from the instrumented
* code. Such package may need to be exported from a module.
*
* @return package name
*/
String collectorPackage();
}
| 939 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
InstrumentationOptions.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/InstrumentationOptions.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.tools.EnvHandler;
import com.sun.tdk.jcov.tools.JCovTool.EnvHandlingException;
import com.sun.tdk.jcov.tools.OptionDescr;
import com.sun.tdk.jcov.util.Utils;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public class InstrumentationOptions {
public final static OptionDescr DSC_TYPE =
new OptionDescr("type", "Type of template.", new String[][]{
{"all", "full information"},
{"branch", "only branches"},
{"block", "only block"},
{"method", "only methods"},},
"Create statistics only for the specified type", "all");
public static final String XML_DEFAULT_TEMPLATE = "template.xml";
public final static OptionDescr DSC_TEMPLATE =
new OptionDescr("template", new String[]{"t"}, "Pre-instrumented template specification.", OptionDescr.VAL_SINGLE,
"Specifies file with xml based template of pre-instrumented classes. Each classfile presented\n"
+ " in this template should be statically instrumented. The instrumentation parameters should be\n"
+ "compatible for static and dynamic instrumentation.", XML_DEFAULT_TEMPLATE);
public final static OptionDescr DSC_MINCLUDE =
new OptionDescr("include_module", new String[]{"im"}, "Filtering conditions.",
OptionDescr.VAL_MULTI, "Specify included classes by regular expression for modules.");
public final static OptionDescr DSC_MEXCLUDE =
new OptionDescr("exclude_module", new String[]{"em"}, "", OptionDescr.VAL_MULTI,
"Specify excluded classes by regular expression for modules.");
public final static OptionDescr DSC_INCLUDE =
new OptionDescr("include", new String[]{"i"}, "Filtering conditions.",
OptionDescr.VAL_MULTI, "Specify included classes by regular expression.");
public final static OptionDescr DSC_EXCLUDE =
new OptionDescr("exclude", new String[]{"e"}, "", OptionDescr.VAL_MULTI,
"Specify excluded classes by regular expression.");
public final static OptionDescr DSC_MINCLUDE_LIST =
new OptionDescr("include_module_list", "", OptionDescr.VAL_SINGLE,
"Specify the path to the file containing module include list. The effect will be the same as\n"
+ "using multiple -include_module options. File should contain one module name mask per line.");
public final static OptionDescr DSC_MEXCLUDE_LIST =
new OptionDescr("exclude_module_list", "", OptionDescr.VAL_SINGLE,
"Specify the path to the file containing module exclude list. The effect will be the same as\n"
+ "using multiple -exclude_module options. File should contain one module name mask per line.");
public final static OptionDescr DSC_INCLUDE_LIST =
new OptionDescr("include_list", "", OptionDescr.VAL_SINGLE,
"Specify the path to the file containing include list. The effect will be the same as\n"
+ "using multiple -include options. File should contain one class name mask per line.");
public final static OptionDescr DSC_EXCLUDE_LIST =
new OptionDescr("exclude_list", "", OptionDescr.VAL_SINGLE,
"Specify the path to the file containing exclude list. The effect will be the same as\n"
+ "using multiple -exclude options. File should contain one class name mask per line.");
public final static OptionDescr DSC_FM =
new OptionDescr("fm", "", OptionDescr.VAL_MULTI,
"Class must have <modifier> to be included in report");
public final static OptionDescr DSC_FM_LIST =
new OptionDescr("fm_list", "", OptionDescr.VAL_SINGLE,
"Specify the path to the file containing modifiers list. The \n"
+ "effect will be the same as using multiple -fm options.\n"
+ "File should contain one class name mask per line.");
public final static OptionDescr DSC_CALLER_INCLUDE =
new OptionDescr("caller_include", new String[]{"ci"}, "", OptionDescr.VAL_MULTI,
"Specify caller filter classes by regular expression.", ".*");
public final static OptionDescr DSC_CALLER_EXCLUDE =
new OptionDescr("caller_exclude", new String[]{"ce"}, "", OptionDescr.VAL_MULTI,
"Specify caller filter classes by regular expression.", "");
public final static OptionDescr DSC_ABSTRACT =
new OptionDescr("abstract", "Specify which items should be additionally included in template.",
new String[][]{
{"on", "abstract methods are counted by their direct invocation"},
{"off", "abstract methods are not counted and not included int report"},}, "Specify should be abstract method included in template.", "off");
public final static OptionDescr DSC_NATIVE =
new OptionDescr("native", "", new String[][]{
{"on", "native methods are counted and included in report"},
{"off", "native methods are not counted and not included int report"}
}, "Specify should be native method included in template.", "on");
public final static OptionDescr DSC_FIELD =
new OptionDescr("field", "", new String[][]{
{"on", "field reading is counted"},
{"off", "field coverage is not counted, fields are not included in report"}
},
"Specify should be fields included in template.", "off");
public final static OptionDescr DSC_SYNTHETIC =
new OptionDescr("synthetic", "", new String[][]{
{"on", "synthetic methods are counted"},
{"off", "synthetic methods are not counted and are not included in report"}
},
"Specify should be synthetic methods included in template.", "on");
public final static OptionDescr DSC_ANONYM =
new OptionDescr("anonym", "", new String[][]{
{"on", "anonymous classes are counted"},
{"off", "anonymous classes are not counted and are not included in report"}
}, "Allows to filter anonymous classes", "on");
public final static OptionDescr DSC_CLASSESRELOAD =
new OptionDescr("classesreload", "", new String[][]{
{"on", "classes could be reloaded. Hash is needed in dynamic mode"},
{"off", "classes will not be reloaded"}
}, "Allows to keep instrumented classes for reusing", "off");
public final static OptionDescr DSC_MERGE =
new OptionDescr("merge", "", new String[][]{
{"merge", "standard merge (summary coverage)"},
{"overwrite", "overwrite existing file"},
{"gensuff", "generate suffix as current time in milliseconds"},
{"scale", "scaled merge (coverage information for individual tests is available)"}
},
"Specify behaviour if output file already exists. Doesn't affects network-based\n"
+ "saving. The merge and scale methods could cause errors if existing file could not be read.", "merge");
public final static OptionDescr DSC_SAVE_BEGIN =
new OptionDescr("savebegin", "Save points.", OptionDescr.VAL_MULTI,
"Initiate saving Jcov data at the beginning of each method specified by this regexp ,\n"
+ "before the first instruction of the method is executed. The signature of method doen't used.");
public final static OptionDescr DSC_SAVE_AT_END =
new OptionDescr("saveatend", "", OptionDescr.VAL_MULTI,
"Work similar savebegin, however save before last instruction in the method is executed (throw or return).\n"
+ "This method doesn't work if exception was thrown not directly in this method.");
public final static OptionDescr DSC_INNERINVOCATION =
new OptionDescr("innerinvocation", "Inner invocations", new String[][]{
{"on", "count inner invocations in the product"},
{"off", "count only invocations outside the instrumented product"}
}, "Allows to filter inner invocations in the instrumented product", "on");
public final static OptionDescr DSC_INNER_INCLUDE =
new OptionDescr("inner_include", new String[]{"ii"}, "", OptionDescr.VAL_MULTI,
"Specify included classes by regular expression for adding inner invocations instrumentation\n" +
"(only for innerinvocation off)");
public final static OptionDescr DSC_INNER_EXCLUDE =
new OptionDescr("inner_exclude", new String[]{"ie"}, "", OptionDescr.VAL_MULTI,
"Specify excluded classes by regular expression, no inner invocations instrumentation will be\n" +
"added to the specified classes (only for innerinvocation off)");
public final static OptionDescr DSC_INSTR_PLUGIN =
new OptionDescr("instr_plugin", new String[0], "Instrumentation plugin", OptionDescr.VAL_SINGLE,
"Defines instrumentation to be performed additionaly to already performed by JCov");
public static enum ABSTRACTMODE {
NONE, IMPLEMENTATION, DIRECT
};
public static enum InstrumentationMode {
METHOD, BLOCK, BRANCH;
public static InstrumentationMode fromString(String mode) {
if (mode.equalsIgnoreCase("method")) {
return METHOD;
} else if (mode.equalsIgnoreCase("block")) {
return BLOCK;
} else if (mode.equalsIgnoreCase("branch")) {
return BRANCH;
} else if (mode.equalsIgnoreCase("all")) {
return BRANCH;
} else {
throw new Error("Unknown instrumentation type.");
}
}
};
public static enum MERGE {
OVERWRITE, MERGE, SCALE, GEN_SUFF
};
public static final String nativePrefix = "$$generated$$_";
public static String concatRegexps(String[] args) {
if (args == null || args.length == 0) {
return "";
}
String result = "";
for (String arg : args) {
result += "|" + arg;
}
return result.substring(1);
}
public static boolean isSkipped(String className, String methodName, int modifier) {
if (className.equals("java/lang/Thread")
&& (methodName.equals("currentThread") || methodName.equals("getId"))) {
return true;
}
return false;
}
public static String[] handleInclude(EnvHandler opts) throws EnvHandlingException {
Set<String> includeSet = new TreeSet<String>();
String[] s;
if (opts.isSet(InstrumentationOptions.DSC_INCLUDE)) {
s = opts.getValues(InstrumentationOptions.DSC_INCLUDE);
if (s != null) {
includeSet.addAll(Arrays.asList(s));
}
}
if (opts.isSet(InstrumentationOptions.DSC_INCLUDE_LIST)) {
try {
s = Utils.readLines(opts.getValue(InstrumentationOptions.DSC_INCLUDE_LIST));
if (s != null) {
includeSet.addAll(Arrays.asList(s));
}
} catch (IOException ex) {
throw new EnvHandlingException("Error while reading include list " + opts.getValue(InstrumentationOptions.DSC_INCLUDE_LIST), ex);
}
}
return includeSet.toArray(new String[includeSet.size()]);
}
public static String[] handleMInclude(EnvHandler opts) throws EnvHandlingException {
Set<String> includeSet = new TreeSet<String>();
String[] s;
if (opts.isSet(InstrumentationOptions.DSC_MINCLUDE)) {
s = opts.getValues(InstrumentationOptions.DSC_MINCLUDE);
if (s != null) {
includeSet.addAll(Arrays.asList(s));
}
}
if (opts.isSet(InstrumentationOptions.DSC_MINCLUDE_LIST)) {
try {
s = Utils.readLines(opts.getValue(InstrumentationOptions.DSC_MINCLUDE_LIST));
if (s != null) {
includeSet.addAll(Arrays.asList(s));
}
} catch (IOException ex) {
throw new EnvHandlingException("Error while reading module include list " + opts.getValue(InstrumentationOptions.DSC_INCLUDE_LIST), ex);
}
}
return includeSet.toArray(new String[includeSet.size()]);
}
public static String[] handleInnerInclude(EnvHandler opts) throws EnvHandlingException {
Set<String> includeSet = new TreeSet<String>();
String[] s;
if (opts.isSet(InstrumentationOptions.DSC_INNER_INCLUDE)) {
s = opts.getValues(InstrumentationOptions.DSC_INNER_INCLUDE);
if (s != null) {
includeSet.addAll(Arrays.asList(s));
}
}
return includeSet.toArray(new String[includeSet.size()]);
}
public static String[] handleInnerExclude(EnvHandler opts) throws EnvHandlingException {
Set<String> excludeSet = new TreeSet<String>();
String[] s = opts.getValues(InstrumentationOptions.DSC_INNER_EXCLUDE);
if (s != null) {
excludeSet.addAll(Arrays.asList(s));
}
return excludeSet.toArray(new String[excludeSet.size()]);
}
public static String[] handleExclude(EnvHandler opts) throws EnvHandlingException {
Set<String> excludeSet = new TreeSet<String>();
String[] s = opts.getValues(InstrumentationOptions.DSC_EXCLUDE);
if (s != null) {
excludeSet.addAll(Arrays.asList(s));
}
if (opts.isSet(InstrumentationOptions.DSC_EXCLUDE_LIST)) {
try {
s = Utils.readLines(opts.getValue(InstrumentationOptions.DSC_EXCLUDE_LIST));
if (s != null) {
excludeSet.addAll(Arrays.asList(s));
}
} catch (IOException ex) {
throw new EnvHandlingException("Error while reading exclude list " + opts.getValue(InstrumentationOptions.DSC_EXCLUDE_LIST), ex);
}
}
return excludeSet.toArray(new String[excludeSet.size()]);
}
public static String[] handleMExclude(EnvHandler opts) throws EnvHandlingException {
Set<String> excludeSet = new TreeSet<String>();
String[] s = opts.getValues(InstrumentationOptions.DSC_MEXCLUDE);
if (s != null) {
excludeSet.addAll(Arrays.asList(s));
}
if (opts.isSet(InstrumentationOptions.DSC_MEXCLUDE_LIST)) {
try {
s = Utils.readLines(opts.getValue(InstrumentationOptions.DSC_MEXCLUDE_LIST));
if (s != null) {
excludeSet.addAll(Arrays.asList(s));
}
} catch (IOException ex) {
throw new EnvHandlingException("Error while reading module exclude list " + opts.getValue(InstrumentationOptions.DSC_EXCLUDE_LIST), ex);
}
}
return excludeSet.toArray(new String[excludeSet.size()]);
}
public static String[] handleFM(EnvHandler opts) throws EnvHandlingException {
Set<String> fmSet = new TreeSet<String>();
String[] s;
if (opts.isSet(InstrumentationOptions.DSC_FM)) {
s = opts.getValues(InstrumentationOptions.DSC_FM);
if (s != null) {
fmSet.addAll(Arrays.asList(s));
}
}
if (opts.isSet(InstrumentationOptions.DSC_FM_LIST)) {
try {
s = Utils.readLines(opts.getValue(InstrumentationOptions.DSC_FM_LIST));
if (s != null) {
fmSet.addAll(Arrays.asList(s));
}
} catch (IOException ex) {
throw new EnvHandlingException("Error while reading exclude list " + opts.getValue(InstrumentationOptions.DSC_EXCLUDE_LIST), ex);
}
}
return fmSet.toArray(new String[fmSet.size()]);
}
}
| 17,422 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataAnnotated.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/DataAnnotated.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
/**
* Class to collect runtime annotations
*
* @author Dmitry Fazunenko
*/
public abstract class DataAnnotated extends DataAbstract {
DataAnnotated(int rootId) {
super(rootId);
}
private List<String> annotations;
/**
*
* @param anno
*/
public void addAnnotation(String anno) {
if (annotations == null) {
annotations = new ArrayList<String>();
}
annotations.add(anno);
}
protected boolean hasAnnotation(String anno) {
return annotations != null && annotations.contains(anno);
}
public List<String> getAnnotations() {
return annotations;
}
void writeObject(DataOutput out) throws IOException {
if (annotations != null) {
out.writeShort(annotations.size());
for (String s : annotations) {
out.writeUTF(s);
}
} else {
out.writeShort(Short.MAX_VALUE);
}
}
DataAnnotated(int rootID, DataInput in) throws IOException {
super(rootID);
int annoNum = in.readShort();
if (annoNum != Short.MAX_VALUE) {
annotations = new ArrayList<String>(annoNum);
for (int i = 0; i < annoNum; ++i) {
String s = in.readUTF();
annotations.add(s);
}
} else {
annotations = null;
}
}
} | 2,786 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CharacterRangeTable.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/CharacterRangeTable.java | /*
* Copyright (c) 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.reader.Reader;
import com.sun.tdk.jcov.instrument.reader.ReaderFactory;
/**
* CharacterRangeTableAttribute
*
*
*
* @author Robert Field
*/
public class CharacterRangeTable {
public static class CRTEntry extends LocationConcrete {
public final int char_start;
public final int char_end;
public final int flags;
public static final int CRT_STATEMENT = 0x0001;
public static final int CRT_BLOCK = 0x0002;
public static final int CRT_ASSIGNMENT = 0x0004;
public static final int CRT_FLOW_CONTROLLER = 0x0008;
public static final int CRT_FLOW_TARGET = 0x0010;
public static final int CRT_INVOKE = 0x0020;
public static final int CRT_CREATE = 0x0040;
public static final int CRT_BRANCH_TRUE = 0x0080;
public static final int CRT_BRANCH_FALSE = 0x0100;
public CRTEntry(final int rootId,
final int start_pc,
final int end_pc,
final int char_start,
final int char_end,
final int flags) {
super(rootId, start_pc, end_pc);
this.char_start = char_start;
this.char_end = char_end;
this.flags = flags;
}
/**
* XML Generation
*/
public String kind() {
return XmlNames.RANGE;
}
public void xmlAttrs(XmlContext ctx) {
super.xmlAttrs(ctx);
if ((flags & CRT_STATEMENT) != 0) {
ctx.attr(XmlNames.A_STATEMENT, true);
}
if ((flags & CRT_BLOCK) != 0) {
ctx.attr(XmlNames.A_BLOCK, true);
}
if ((flags & CRT_ASSIGNMENT) != 0) {
ctx.attr(XmlNames.A_ASSIGNMENT, true);
}
if ((flags & CRT_FLOW_CONTROLLER) != 0) {
ctx.attr(XmlNames.A_CONTROLLER, true);
}
if ((flags & CRT_FLOW_TARGET) != 0) {
ctx.attr(XmlNames.A_TARGET, true);
}
if ((flags & CRT_INVOKE) != 0) {
ctx.attr(XmlNames.A_INVOKE, true);
}
if ((flags & CRT_CREATE) != 0) {
ctx.attr(XmlNames.A_CREATE, true);
}
if ((flags & CRT_BRANCH_TRUE) != 0) {
ctx.attr(XmlNames.A_BRANCHTRUE, true);
}
if ((flags & CRT_BRANCH_FALSE) != 0) {
ctx.attr(XmlNames.A_BRANCHFALSE, true);
}
}
private void xmlPos(XmlContext ctx, int char_pos) {
ctx.indent();
ctx.format("<" + XmlNames.CRT_POS + " " + XmlNames.CRT_LINE + "='%d' "
+ XmlNames.CRT_COL + "='%d'/>", char_pos >> 10, char_pos & 0x3FF);
ctx.println();
}
void xmlBody(XmlContext ctx) {
xmlPos(ctx, char_start);
xmlPos(ctx, char_end);
}
}
public int length;
public CRTEntry[] entries;
private int rootId;
public int getRootId() {
return rootId;
}
public void setRootId(int rootId) {
this.rootId = rootId;
}
/**
* Creates a new instance of CharacterRangeTableAttribute
*/
public CharacterRangeTable(int rootId) {
this(rootId, 0, new CRTEntry[0]);
}
public CharacterRangeTable(int rootId, int length, CRTEntry[] entries) {
this.length = length;
this.entries = entries;
this.rootId = rootId;
}
public CRTEntry[] getEntries() {
return entries;
}
public void setEntries(CRTEntry[] entries) {
this.entries = entries;
}
/*
* return entry with given pc and flag set,
* if there are more then one found , return first in source code
*/
CRTEntry getEntry(int pc, int flag) {
CRTEntry result = null;
for (CRTEntry entry : getEntries()) {
if (entry.startBCI() == pc
&& (entry.flags & flag) != 0) {
result = (result == null) ? entry
: entry.char_start < result.char_start ? entry : result;
}
}
return result;
}
/**
* XML Generation
*
* Since there is no multiple inheritance, we aren't a DataAbstract, but
* we'll fake it
*/
public void xmlGen(XmlContext ctx) {
ctx.indent();
ctx.println("<" + XmlNames.CRT + ">");
ctx.incIndent();
for (CRTEntry entry : entries) {
entry.xmlGen(ctx);
}
ctx.decIndent();
ctx.indent();
ctx.println("</" + XmlNames.CRT + ">");
}
public void readDataFrom() throws FileFormatException {
ReaderFactory rf = DataRoot.getInstance(rootId).getReaderFactory();
Reader r = rf.getReaderFor(this);
r.readData(this);
}
public int getPos(int line, int col) {
return line << 10 | col;
}
} | 6,258 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBranchSwitchStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataBranchSwitchStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataBlockTargetCase;
import com.sun.tdk.jcov.instrument.DataBlockTargetDefault;
import com.sun.tdk.jcov.instrument.DataBranchSwitch;
import com.sun.tdk.jcov.instrument.XmlNames;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataBranchSwitchStAX implements Reader {
private DataBranchSwitch swtch;
private XMLStreamReader parser;
public void readData(Object dest) throws FileFormatException {
swtch = (DataBranchSwitch) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException, FileFormatException {
// super.readDataFrom(parser, refs, mode);
while (!(parser.getEventType() == XMLStreamConstants.END_ELEMENT
&& parser.getLocalName() == XmlNames.SWITHCH)) {
parser.nextTag();
String elem = parser.getLocalName();
if (elem == XmlNames.DEFAULT) {
DataBlockTargetDefault def = new DataBlockTargetDefault(swtch.rootId(), 0, false, 0);
def.readDataFrom();
swtch.setDefault(def);
swtch.addTarget(def);
parser.nextTag();
} else if (elem == XmlNames.CASE) {
int val = Integer.parseInt(parser.getAttributeValue(null, XmlNames.VALUE));
DataBlockTargetCase cs = new DataBlockTargetCase(swtch.rootId(), val,
0, false, 0);
cs.readDataFrom();
swtch.addTarget(cs);
parser.nextTag();
}
}
}
public void setReaderFactory(ReaderFactory r) {
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 3,203 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataClassStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataClassStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.instrument.DataMethod;
import com.sun.tdk.jcov.instrument.DataMethodEntryOnly;
import com.sun.tdk.jcov.instrument.DataMethodInvoked;
import com.sun.tdk.jcov.instrument.DataMethodWithBlocks;
import com.sun.tdk.jcov.instrument.XmlNames;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataClassStAX implements Reader {
private XMLStreamReader parser;
private ReaderFactory rf;
private DataClass clazz;
public void readData(Object dest) throws FileFormatException {
clazz = (DataClass) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
final void readData() throws XMLStreamException, FileFormatException {
clazz.setSuperName(parser.getAttributeValue(null, XmlNames.SUPERNAME));
clazz.setSource(parser.getAttributeValue(null, XmlNames.SOURCE));
boolean end = false;
while (!end) {
int type = parser.nextTag();
switch (type) {
case XMLStreamConstants.START_ELEMENT:
if (parser.getLocalName() == XmlNames.METHOD) {
parseMethod(parser);
} else {
parseField(parser);
}
break;
case XMLStreamConstants.END_ELEMENT:
end = true;
break;
}
}
}
private void parseMethod(XMLStreamReader parser) throws XMLStreamException, FileFormatException {
String name = parser.getAttributeValue(null, XmlNames.NAME);
String vmSig = parser.getAttributeValue(null, XmlNames.VMSIG);
String flags = parser.getAttributeValue(null, XmlNames.FLAGS);
int access = Integer.parseInt(parser.getAttributeValue(null, XmlNames.ACCESS));
String signature = parser.getAttributeValue(null, XmlNames.SIGNATURE);
int id = 0;
String s = parser.getAttributeValue(null, XmlNames.ID);
if (s != null) {
id = Integer.parseInt(s);
}
long count = 0;
s = parser.getAttributeValue(null, XmlNames.COUNT);
if (s != null) {
count = Long.parseLong(s);
}
int length = 0;
s = parser.getAttributeValue(null, XmlNames.LENGTH);
if (s != null) {
length = Integer.parseInt(s);
}
String scale = parser.getAttributeValue(null, XmlNames.SCALE);
parser.nextTag();
DataMethod mthd;
if (parser.getEventType() == XMLStreamConstants.END_ELEMENT) {
if (flags.contains("native")
|| flags.contains("abstract")) {
DataMethodInvoked m = new DataMethodInvoked(clazz, access,
name, vmSig, signature,
new String[0], id);
m.setCount(count);
m.setScale(scale);
mthd = m;
} else {
DataMethodEntryOnly m = new DataMethodEntryOnly(clazz, access,
name, vmSig, signature,
new String[0], id);//method exceptions aren't stored in xml
m.setCount(count);
m.setScale(scale);
mthd = m;
}
}
else {
DataMethodWithBlocks m = new DataMethodWithBlocks(clazz, access,
name, vmSig, signature,
new String[0]);//method exceptions aren't stored in xml
m.setBytecodeLength(length);
m.readDataFrom();
mthd = m;
}
}
private void parseField(XMLStreamReader parser) throws XMLStreamException, FileFormatException {
String name = parser.getAttributeValue(null, XmlNames.NAME);
String vmSig = parser.getAttributeValue(null, XmlNames.VMSIG);
String flags = parser.getAttributeValue(null, XmlNames.FLAGS);
int access = Integer.parseInt(parser.getAttributeValue(null, XmlNames.ACCESS));
int id = Integer.parseInt(parser.getAttributeValue(null, XmlNames.ID));
String val = parser.getAttributeValue(null, XmlNames.VALUE);
DataField field = new DataField(clazz, access,
name, vmSig, clazz.getSignature(),
val, id);
field.readDataFrom();
}
public void setReaderFactory(ReaderFactory r) {
rf = r;
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 6,024 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataMethodWithBlocksStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataMethodWithBlocksStAX.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.BasicBlock;
import com.sun.tdk.jcov.instrument.CharacterRangeTable;
import com.sun.tdk.jcov.instrument.DataAbstract.LocationCoords;
import com.sun.tdk.jcov.instrument.DataMethodWithBlocks;
import com.sun.tdk.jcov.instrument.DataRoot;
import com.sun.tdk.jcov.instrument.LocationRef;
import com.sun.tdk.jcov.instrument.InstrumentationOptions.InstrumentationMode;
import com.sun.tdk.jcov.instrument.SimpleBasicBlock;
import com.sun.tdk.jcov.instrument.XmlNames;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataMethodWithBlocksStAX implements Reader {
private DataMethodWithBlocks meth;
private XMLStreamReader parser;
private ReaderFactory rf;
public void readData(Object dest) throws FileFormatException {
meth = (DataMethodWithBlocks) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException, FileFormatException {
List<BasicBlock> blocks = new LinkedList();
Map<LocationCoords, List<LocationRef>> refs = new HashMap();//TreeMap();//HashTable!!!
rf.setProcessingData(refs);
while (!(parser.getEventType() == XMLStreamConstants.END_ELEMENT
&& XmlNames.METHOD.equals(parser.getLocalName()))) {
String elem = parser.getLocalName();
if (XmlNames.BLOCK.equals(elem)) {
BasicBlock bb;
InstrumentationMode mode = DataRoot.getInstance(meth.rootId()).getParams().getMode();
if (mode.equals(InstrumentationMode.BLOCK)) {
int start = Integer.parseInt(parser.getAttributeValue(null, XmlNames.START));
int end = Integer.parseInt(parser.getAttributeValue(null, XmlNames.END));
bb = new SimpleBasicBlock(meth.rootId(), start, end, false);
} else {
bb = new BasicBlock(meth.rootId());
}
bb.readDataFrom();
blocks.add(bb);
} else if (XmlNames.METHENTER.equals(elem)) { // occures when instrmode == block
int start = 0;
String s = parser.getAttributeValue(null, XmlNames.START);
if (s != null) {
start = Integer.parseInt(s);
}
int end = 0;
s = parser.getAttributeValue(null, XmlNames.END);
if (s != null) {
end = Integer.parseInt(s);
}
BasicBlock bb = new SimpleBasicBlock(meth.rootId(), start, end, false);
bb.readDataFrom();
blocks.add(bb);
} else if (XmlNames.CRT.equals(elem)) {
meth.setCharacterRangeTable(new CharacterRangeTable(meth.rootId()));
meth.getCharacterRangeTable().readDataFrom();
} else {
Reader r = rf.getSuperReaderFor(DataMethodWithBlocks.class);
r.readData(meth);
}
parser.nextTag();
}
for (LocationCoords c : refs.keySet()) {
for (BasicBlock b : blocks) {
if (b.startBCI() == c.start && b.endBCI() == c.end) {
for (LocationRef ref : refs.get(c)) {
ref.setConcreteLocation(b);
}
break;
}
}
}
meth.setBasicBlocks(blocks.toArray(new BasicBlock[blocks.size()]));
}
public void setReaderFactory(ReaderFactory r) {
rf = r;
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 5,216 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ReaderFactory.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/ReaderFactory.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import java.io.InputStream;
import java.util.HashMap;
/**
*
* @author Sergey Borodin
*/
public abstract class ReaderFactory {
protected int javaVersion;
protected HashMap<Class, Reader> readers;
protected Object processingData;
public static ReaderFactory newInstance(int javaVersion, InputStream is) {
String rName = ReaderFactory.class.getName();
rName += "StAX";
try {
ReaderFactory r = (ReaderFactory) Class.forName(rName).newInstance();
r.javaVersion = javaVersion;
r.setDataSource(is);
r.readers = new HashMap();
return r;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public void setProcessingData(Object data) {
processingData = data;
}
public Object getProcessingData() {
return processingData;
}
abstract void setDataSource(InputStream is) throws FileFormatException;
abstract String getReadersSuffix();
public Reader getReaderFor(Object o) throws FileFormatException {
Class c = o.getClass();
return getReaderForClass(c);
}
public Reader getSuperReaderFor(Class c) throws FileFormatException {
Class superC = c.getSuperclass();
return getReaderForClass(superC);
}
private Reader getReaderForClass(Class c) throws FileFormatException {
if (readers.get(c) != null) {
return readers.get(c);
}
try {
String rName = c.getPackage().getName() + ".reader." + c.getSimpleName() + getReadersSuffix();
Reader r = (Reader) Class.forName(rName).newInstance();
r.setReaderFactory(this);
readers.put(c, r);
return r;
} catch (ClassNotFoundException ex) {
Class superClass = c.getSuperclass();
if (superClass != null && !Object.class.equals(superClass)) {
return getReaderForClass(superClass);
}
return null;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
| 3,453 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
LocationRefStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/LocationRefStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataAbstract.LocationCoords;
import com.sun.tdk.jcov.instrument.LocationRef;
import com.sun.tdk.jcov.instrument.XmlNames;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class LocationRefStAX implements Reader {
private LocationRef ref;
private XMLStreamReader parser;
private ReaderFactory rf;
public void readData(Object dest) throws FileFormatException {
ref = (LocationRef) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex.getMessage());
}
}
void readData() throws XMLStreamException {
LocationCoords c = new LocationCoords();
c.start = Integer.parseInt(parser.getAttributeValue(null, XmlNames.START));
c.end = Integer.parseInt(parser.getAttributeValue(null, XmlNames.END));
Map<LocationCoords, List<LocationRef>> refs =
(Map<LocationCoords, List<LocationRef>>) rf.getProcessingData();
List<LocationRef> l = refs.get(c);
if (l == null) {
l = new LinkedList();
refs.put(c, l);
}
l.add(ref);
}
public void setReaderFactory(ReaderFactory r) {
rf = r;
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 2,750 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBranchGotoStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataBranchGotoStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataBlockTarget;
import com.sun.tdk.jcov.instrument.DataBlockTargetGoto;
import com.sun.tdk.jcov.instrument.DataBranchGoto;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataBranchGotoStAX implements Reader {
private DataBranchGoto gt;
private XMLStreamReader parser;
private ReaderFactory rf;
public void readData(Object dest) throws FileFormatException {
gt = (DataBranchGoto) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException, FileFormatException {
// super.readDataFrom(parser, refs, mode);
parser.nextTag();
DataBlockTarget target = new DataBlockTargetGoto(gt.rootId(), 0, false, 0);
target.readDataFrom();
gt.addTarget(target);
parser.nextTag();//end of target
parser.nextTag();//end of goto
}
public void setReaderFactory(ReaderFactory r) {
rf = r;
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 2,484 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBranchCondStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataBranchCondStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataBlockTargetCond;
import com.sun.tdk.jcov.instrument.DataBranchCond;
import com.sun.tdk.jcov.instrument.XmlNames;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataBranchCondStAX implements Reader {
private DataBranchCond cond;
private XMLStreamReader parser;
private ReaderFactory rf;
public void readData(Object dest) throws FileFormatException {
cond = (DataBranchCond) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException, FileFormatException {
// super.readDataFrom(parser, refs, mode);
parser.nextTag();
boolean isVal = Boolean.parseBoolean(parser.getAttributeValue(null, XmlNames.VALUE));
DataBlockTargetCond cond1 = new DataBlockTargetCond(cond.rootId(), isVal,
0, false, 0);
cond1.readDataFrom();
parser.nextTag();//end cond
parser.nextTag();
isVal = Boolean.parseBoolean(parser.getAttributeValue(null, XmlNames.VALUE));
DataBlockTargetCond cond2 = new DataBlockTargetCond(cond.rootId(), isVal,
0, false, 0);
cond2.readDataFrom();
parser.nextTag();//end cond
if (cond1.isFallenInto()) {
cond.addTarget(cond2);
cond.addTarget(cond1);
} else {
cond.addTarget(cond1);
cond.addTarget(cond2);
}
parser.nextTag();//end br
}
public void setReaderFactory(ReaderFactory r) {
rf = r;
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 3,060 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ReaderFactoryStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/ReaderFactoryStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import java.io.InputStream;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class ReaderFactoryStAX extends ReaderFactory {
protected XMLStreamReader parser;
@Override
void setDataSource(InputStream is) throws FileFormatException {
XMLInputFactory factory = XMLInputFactory.newInstance();
try {
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
parser = factory.createXMLStreamReader(is);
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
@Override
String getReadersSuffix() {
return "StAX";
}
}
| 2,148 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataFieldStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataFieldStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.data.Scale;
import com.sun.tdk.jcov.data.ScaleOptions;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.instrument.DataRoot;
import com.sun.tdk.jcov.instrument.XmlNames;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataFieldStAX implements Reader {
private DataField fld;
private XMLStreamReader parser;
private ReaderFactory rf;
public void readData(Object dest) throws FileFormatException {
fld = (DataField) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex.getMessage());
}
}
void readData() throws XMLStreamException, FileFormatException {
if (fld.getParent().getSource() != null && fld.getParent().getSource().endsWith(".fx")) {
Reader r = rf.getSuperReaderFor(DataField.class);
r.readData(fld);
}
long count = 0;
String s = parser.getAttributeValue(null, XmlNames.COUNT);
if (s != null) {
count = Long.parseLong(s);
}
fld.setCount(count);
readScale();
fld.setSignature(parser.getAttributeValue(null, XmlNames.SIGNATURE));
parser.nextTag();
}
private void readScale() {
String s = parser.getAttributeValue(null, XmlNames.SCALE);
if (s != null && s.length() > 0) {
try {
DataRoot r = DataRoot.getInstance(fld.rootId());
ScaleOptions opts = r.getScaleOpts();
if (opts.needReadScales()) {
fld.setScale(new Scale(s.toCharArray(), s.length(),
opts.getScaleSize(), opts.getScaleCompressor(), opts.scalesCompressed()));
}
} catch (FileFormatException ex) {
}
}
}
public void setReaderFactory(ReaderFactory r) {
rf = r;
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 3,356 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CharacterRangeTableAttributeStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/CharacterRangeTableAttributeStAX.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.CharacterRangeTable;
import com.sun.tdk.jcov.instrument.CharacterRangeTable.CRTEntry;
import com.sun.tdk.jcov.instrument.XmlNames;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class CharacterRangeTableAttributeStAX implements Reader {
CharacterRangeTable crt;
private XMLStreamReader parser;
public void readData(Object dest) throws FileFormatException {
crt = (CharacterRangeTable) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException {
parser.nextTag();
List<CRTEntry> entriesList = new ArrayList();
while (!(parser.getEventType() == XMLStreamConstants.END_ELEMENT
&& parser.getLocalName() == XmlNames.CRT)) {
String elem = parser.getLocalName();
if (elem == XmlNames.RANGE) {
int flags = getFlags(parser);
int start = Integer.parseInt(parser.getAttributeValue(null, XmlNames.START));
int end = Integer.parseInt(parser.getAttributeValue(null, XmlNames.END));
parser.nextTag();//come into <pos
int ch_start = crt.getPos(Integer.parseInt(parser.getAttributeValue(null, XmlNames.CRT_LINE)),
Integer.parseInt(parser.getAttributeValue(null, XmlNames.CRT_COL)));
parser.nextTag();//end of <pos
parser.nextTag();//second <pos
int ch_end = crt.getPos(Integer.parseInt(parser.getAttributeValue(null, XmlNames.CRT_LINE)),
Integer.parseInt(parser.getAttributeValue(null, XmlNames.CRT_COL)));
CRTEntry e = new CRTEntry(crt.getRootId(), start, end, ch_start, ch_end, flags);
entriesList.add(e);
parser.nextTag();//end of <pos
parser.nextTag();//end of range
}
parser.nextTag();//next elem, may be </crt>
}
crt.setEntries(entriesList.toArray(new CRTEntry[entriesList.size()]));
}
public int getFlags(XMLStreamReader parser) {
int flags = 0;
for (int i = 0; i < parser.getAttributeCount(); i++) {
String name = parser.getAttributeLocalName(i);
if (name.equals(XmlNames.A_STATEMENT)) {
flags |= CRTEntry.CRT_STATEMENT;
} else if (name.equals(XmlNames.A_BLOCK)) {
flags |= CRTEntry.CRT_BLOCK;
} else if (name.equals(XmlNames.A_CONTROLLER)) {
flags |= CRTEntry.CRT_FLOW_CONTROLLER;
} else if (name.equals(XmlNames.A_TARGET)) {
flags |= CRTEntry.CRT_FLOW_TARGET;
} else if (name.equals(XmlNames.A_BRANCHTRUE)) {
flags |= CRTEntry.CRT_BRANCH_TRUE;
} else if (name.equals(XmlNames.A_BRANCHFALSE)) {
flags |= CRTEntry.CRT_BRANCH_FALSE;
}
}
return flags;
}
public void setReaderFactory(ReaderFactory r) {
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 4,617 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
LocationConcreteStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/LocationConcreteStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.LocationConcrete;
import com.sun.tdk.jcov.instrument.XmlNames;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class LocationConcreteStAX implements Reader {
LocationConcrete lc;
private XMLStreamReader parser;
public void readData(Object dest) throws FileFormatException {
lc = (LocationConcrete) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException {
lc.setStartBCI(Integer.parseInt(parser.getAttributeValue(null, XmlNames.START)));
lc.setEndBCI(Integer.parseInt(parser.getAttributeValue(null, XmlNames.END)));
}
public void setReaderFactory(ReaderFactory r) {
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 2,229 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataAnnotatedStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataAnnotatedStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataAnnotated;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataAnnotatedStAX implements Reader {
private DataAnnotated anno;
private XMLStreamReader parser;
public void readData(Object dest) throws FileFormatException {
anno = (DataAnnotated) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException {
}
public void setReaderFactory(ReaderFactory r) {
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 2,008 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataRootStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataRootStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataRoot;
import com.sun.tdk.jcov.instrument.InstrumentationOptions.ABSTRACTMODE;
import com.sun.tdk.jcov.instrument.InstrumentationOptions.InstrumentationMode;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import com.sun.tdk.jcov.instrument.XmlNames;
import java.util.TreeMap;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataRootStAX implements RootReader {
XMLStreamReader parser;
DataRoot root;
public void readData(Object dest) throws FileFormatException {
root = (DataRoot) dest;
try {
readData();
} catch (XMLStreamException ex) {
if ("ParseError at [row,col]:[1,1]\nMessage: Premature end of file.".equals(ex.getMessage())) {
throw new FileFormatException("File is empty");
} else {
if (ex.getMessage() != null) {
int i = ex.getMessage().indexOf("Message: ");
if (i < 0) {
throw new FileFormatException("Malformed xml file {0} - " + ex.getMessage());
} else {
throw new FileFormatException("Malformed xml file {0} - " + ex.getMessage().substring(i + 9));
}
}
}
throw new FileFormatException(ex);
}
}
private void readData() throws XMLStreamException, FileFormatException {
int event = -1;//before start
while (event != XMLStreamConstants.END_ELEMENT) {
event = parser.nextTag();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
String tagName = parser.getLocalName();
if (tagName.equals(XmlNames.COVERAGE)) {
break;
} else if (tagName.equals(XmlNames.HEAD)) {
readHeader0();
break;
} else if (tagName.equals(XmlNames.PACKAGE)) {
readPackage();
break;
}
default:
break;
}
}
}
private void readPackage() throws XMLStreamException, FileFormatException {
String packName = parser.getAttributeValue(null, XmlNames.NAME);
String moduleName = parser.getAttributeValue(null, XmlNames.MODULE_NAME);
int event = parser.getEventType();
while (true) {
event = parser.nextTag();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
readClass(packName, moduleName);
break;
case XMLStreamReader.END_ELEMENT://end of package
if (parser.getLocalName().equals(XmlNames.PACKAGE)) {//not necessary?!
return;
}
break;
}
}
}
private void readClass(String packName, String moduleName) throws FileFormatException {
String clName = parser.getAttributeValue(null, XmlNames.NAME);
String fullName = packName.isEmpty() ? clName
: packName.replaceAll("\\.", "/") + "/" + clName;
String checksum = parser.getAttributeValue(null, XmlNames.CHECKSUM);
DataClass clazz = new DataClass(root.rootId(), fullName, moduleName,checksum == null ? -1
: Long.parseLong(checksum), root.isDifferentiateElements());
clazz.setInfo(parser.getAttributeValue(null, XmlNames.FLAGS), parser.getAttributeValue(null, XmlNames.SIGNATURE),
parser.getAttributeValue(null, XmlNames.SUPERNAME), parser.getAttributeValue(null, XmlNames.SUPER_INTERFACES));
final String inner = parser.getAttributeValue(null, XmlNames.INNER_CLASS);
if (inner != null) {
if ("inner".equals(inner)) {
clazz.setInner(true);
} else if ("anon".equals(inner)) {
clazz.setInner(true);
clazz.setAnonym(true);
}
}
// if (acceptor == null || acceptor.accepts(clazz)) {
clazz.readDataFrom();
root.addClass(clazz);
// }
}
;
public void readHeader(Object dest) throws FileFormatException {
root = (DataRoot) dest;
try {
readHeader();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
private void readHeader() throws XMLStreamException {
int event = -1;//before start
boolean readHeader = false;
while (!readHeader) {
event = parser.nextTag();
switch (event) {
case XMLStreamConstants.START_ELEMENT:
String tagName = parser.getLocalName();
if (tagName.equals(XmlNames.COVERAGE)) {
break;
} else if (tagName.equals(XmlNames.HEAD)) {
readHeader0();
readHeader = true;
break;
} else if (tagName.equals(XmlNames.PACKAGE)) {
break;//should not occure
}
default:
break;
}
}
}
private void readHeader0() throws XMLStreamException {
TreeMap<String, String> props = new TreeMap();
parser.nextTag();//begin
InstrumentationMode mode = InstrumentationMode.BRANCH;
boolean detectInternal = true;
boolean dynamicCollect = false;
String[] includes = null, excludes = null, callerIncludes = null, callerExcludes = null;
while (parser.getEventType() != XMLStreamReader.END_ELEMENT) {
String name = parser.getAttributeValue(null, XmlNames.NAME);
String value = parser.getAttributeValue(null, XmlNames.VALUE);
if (name.equals("coverage.generator.args")) {
root.setArgs(value);
} else if (name.equals("id.count")) {
root.setCount(Integer.parseInt(value));
} else if (name.equals("coverage.generator.mode")) {
mode = InstrumentationMode.fromString(value);
} else if (name.equals("coverage.generator.internal")) {
detectInternal = "detect".equals(value);
} else if (name.equals("coverage.generator.include")) {
includes = value.split("\\|");
} else if (name.equals("coverage.generator.exclude")) {
excludes = value.split("\\|");
} else if (name.equals("coverage.generator.caller_include")) {
callerIncludes = value.split("\\|");
} else if (name.equals("coverage.generator.caller_exclude")) {
callerExcludes = value.split("\\|");
} else if (name.equals("dynamic.collected")) {
dynamicCollect = Boolean.parseBoolean(value);
} else if (name.equals("scale.size")) {
if (root.getScaleOpts().needReadScales()) {
root.getScaleOpts().setScaleSize(Integer.parseInt(value));
}
} else if (name.equals("scales.compressed")) {
root.getScaleOpts().setScalesCompressed(Boolean.parseBoolean(value));
} else {
props.put(name, value);
}
parser.nextTag();
parser.nextTag();
}
ABSTRACTMODE abstractmode = null;
boolean instrumentNative = false, instrumentFields = false;
root.setParams(new InstrumentationParams(dynamicCollect, instrumentNative, instrumentFields, detectInternal, abstractmode, includes, excludes, callerIncludes, callerExcludes, mode));
root.setXMLHeadProperties(props);
}
public void setReaderFactory(ReaderFactory r) {
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 9,407 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
BasicBlockStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/BasicBlockStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.BasicBlock;
import com.sun.tdk.jcov.instrument.Constants;
import com.sun.tdk.jcov.instrument.DataBlockCatch;
import com.sun.tdk.jcov.instrument.DataBlockFallThrough;
import com.sun.tdk.jcov.instrument.DataBlockMethEnter;
import com.sun.tdk.jcov.instrument.DataBranchCond;
import com.sun.tdk.jcov.instrument.DataBranchGoto;
import com.sun.tdk.jcov.instrument.DataBranchSwitch;
import com.sun.tdk.jcov.instrument.DataExit;
import com.sun.tdk.jcov.instrument.DataExitSimple;
import com.sun.tdk.jcov.instrument.XmlNames;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class BasicBlockStAX implements Reader {
private BasicBlock block;
private XMLStreamReader parser;
private ReaderFactory rf;
public void readData(Object dest) throws FileFormatException {
block = (BasicBlock) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException, FileFormatException {
Reader r = rf.getSuperReaderFor(BasicBlock.class);
r.readData(block);
parser.nextTag();
while (!(parser.getEventType() == XMLStreamConstants.END_ELEMENT
&& parser.getLocalName() == XmlNames.BLOCK)) {
String elem = parser.getLocalName();
if (isXMLDataExit(elem)) {
block.setExit(instantiateExit());
} else {
if (elem == XmlNames.METHENTER) {
DataBlockMethEnter enter = new DataBlockMethEnter(block.rootId(), 0, false, 0);
enter.readDataFrom();
block.add(enter);
} else if (elem == XmlNames.FALL) {
DataBlockFallThrough fall = new DataBlockFallThrough(block.rootId(), 0, false, 0);
fall.readDataFrom();
block.add(fall);
} else if (elem == XmlNames.CATCH) {
DataBlockCatch ctch = new DataBlockCatch(block.rootId(), 0, false, 0);
ctch.readDataFrom();
block.add(ctch);
}
parser.nextTag();
}
// parser.nextTag();//closing internal elem
parser.nextTag();//next elem, may be </bl>
}
}
private boolean isXMLDataExit(String elem) {
if (elem == XmlNames.EXIT
|| elem == XmlNames.SWITHCH
|| elem == XmlNames.GOTO
|| elem == XmlNames.BRANCH) {
return true;
}
return false;
}
private DataExit instantiateExit() throws XMLStreamException, FileFormatException {
DataExit dExit = null;
String elem = parser.getLocalName();
int start = Integer.parseInt(parser.getAttributeValue(null, XmlNames.START));
int end = Integer.parseInt(parser.getAttributeValue(null, XmlNames.END));
if (elem == XmlNames.EXIT) {
int opCode = Constants.getOpCode(parser.getAttributeValue(null, XmlNames.OPCODE));
dExit = new DataExitSimple(block.rootId(), start, end, opCode);
parser.nextTag();
return dExit;
} else if (elem == XmlNames.SWITHCH) {
dExit = new DataBranchSwitch(block.rootId(), start, end);
} else if (elem == XmlNames.GOTO) {
dExit = new DataBranchGoto(block.rootId(), start, end);
} else if (elem == XmlNames.BRANCH) {
dExit = new DataBranchCond(block.rootId(), start, end);
}
dExit.readDataFrom();
return dExit;
}
public void setReaderFactory(ReaderFactory r) {
rf = r;
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 5,184 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataMethodStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataMethodStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataMethod;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataMethodStAX implements Reader {
private DataMethod meth;
private XMLStreamReader parser;
public void readData(Object dest) throws FileFormatException {
meth = (DataMethod) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException {
// if (parser.getLocalName() == "meth") {
// if (k.source != null && k.source.endsWith(".fx")) {
// super.readDataFrom(parser, refs, mode);
// }
// }
// else {
String lt = parser.getElementText();//end lt
if (lt != null) {
String[] pairs = lt.split(";");
String[] pair;
for (String s : pairs) {
pair = s.split("=");
meth.addLineEntry(Integer.parseInt(pair[0]), Integer.parseInt(pair[1]));
}
}
// }
}
public void setReaderFactory(ReaderFactory r) {
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 2,563 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SimpleBasicBlockStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/SimpleBasicBlockStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.SimpleBasicBlock;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class SimpleBasicBlockStAX implements Reader {
private SimpleBasicBlock simpleBlock;
private XMLStreamReader parser;
public void readData(Object dest) throws FileFormatException {
simpleBlock = (SimpleBasicBlock) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException, FileFormatException {
simpleBlock.getBlock().readDataFrom();
simpleBlock.setStartBCI(simpleBlock.getBlock().startBCI());
simpleBlock.setEndBCI(simpleBlock.getBlock().endBCI());
parser.nextTag();
}
public void setReaderFactory(ReaderFactory r) {
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 2,263 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataBlockStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataBlockStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.DataBlock;
import com.sun.tdk.jcov.instrument.XmlNames;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataBlockStAX implements Reader {
private DataBlock block;
private XMLStreamReader parser;
private ReaderFactory rf;
public void readData(Object dest) throws FileFormatException {
block = (DataBlock) dest;
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException, FileFormatException {
Reader r = rf.getSuperReaderFor(DataBlock.class);
r.readData(block);
String id = parser.getAttributeValue(null, XmlNames.ID);
if (id != null) {
block.setId(Integer.parseInt(id));
}
String cnt = parser.getAttributeValue(null, XmlNames.COUNT);
if (cnt != null) {
block.setCount(Long.parseLong(cnt));
}
String s = parser.getAttributeValue(null, XmlNames.SCALE);
if (s != null) {
block.readScale(s);
}
// parser.nextTag();//end
}
public void setReaderFactory(ReaderFactory r) {
rf = r;
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 2,666 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
RootReader.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/RootReader.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
/**
*
* @author Sergey Borodin
*/
public interface RootReader extends Reader {
public void readHeader(Object dest) throws FileFormatException;
}
| 1,456 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Reader.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/Reader.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
/**
*
* @author Sergey Borodin
*/
public interface Reader {
public void readData(Object dest) throws FileFormatException;
public void setReaderFactory(ReaderFactory r);
}
| 1,487 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataExitSimpleStAX.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/reader/DataExitSimpleStAX.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.reader;
import com.sun.tdk.jcov.data.FileFormatException;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
/**
*
* @author Sergey Borodin
*/
public class DataExitSimpleStAX implements Reader {
private XMLStreamReader parser;
public void readData(Object dest) throws FileFormatException {
try {
readData();
} catch (XMLStreamException ex) {
throw new FileFormatException(ex);
}
}
void readData() throws XMLStreamException {
// super.readDataFrom(parser, refs, mode);
parser.nextTag(); //end exit
}
public void setReaderFactory(ReaderFactory r) {
parser = ((ReaderFactoryStAX) r).parser;
}
}
| 1,977 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
OffsetLabelingClassReader.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/OffsetLabelingClassReader.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import java.io.IOException;
import java.io.InputStream;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Label;
/**
* OffsetLabelingClassReader
*
*
* @author Robert Field
*/
class OffsetLabelingClassReader extends ClassReader {
public OffsetLabelingClassReader(byte[] b) {
super(b);
}
public OffsetLabelingClassReader(InputStream in) throws IOException {
super(in);
}
/**
* @Override public void accept(ClassVisitor cv, Attribute[] attrs, int
* flags) { super.accept(new MyClassAdapter(cv), attrs, flags); }
***
*/
@Override
protected Label readLabel(int offset, Label[] labels) {
OffsetLabel label = (OffsetLabel) labels[offset];
if (label == null) {
for (int i = 0; i < labels.length; ++i) {
labels[i] = new OffsetLabel(i);
}
label = (OffsetLabel) labels[offset];
}
label.realLabel = true;
return label;
}
}
| 2,247 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
FieldAnnotationVisitor.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/FieldAnnotationVisitor.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.FieldVisitor;
/**
* Field visitor collecting runtime annotations
*
* @author Dmitry Fazunenko
*/
class FieldAnnotationVisitor extends FieldVisitor {
final DataField field;
final FieldVisitor fv;
FieldAnnotationVisitor(final FieldVisitor fv, final DataField field) {
super(ASMUtils.ASM_API_VERSION, fv);
this.fv = fv;
this.field = field;
}
public void visitAttribute(Attribute arg0) {
fv.visitAttribute(arg0);
}
public void visitEnd() {
fv.visitEnd();
}
public AnnotationVisitor visitAnnotation(String anno, boolean b) {
field.addAnnotation(anno);
return fv.visitAnnotation(anno, b);
}
}
| 2,134 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ASMModifiers.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/ASMModifiers.java | /*
* Copyright (c) 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.Modifiers;
import com.sun.tdk.jcov.instrument.XmlNames;
import static org.objectweb.asm.Opcodes.*;
public class ASMModifiers implements Modifiers {
private final int access;
public ASMModifiers(int access) {
this.access = access;
}
@Override
public int access() { return access & ACCESS_MASK; }
@Override
public boolean is(int flag) { return (access & flag) != 0; }
@Override
public boolean isPublic() { return is(ACC_PUBLIC); }
@Override
public boolean isPrivate() { return is(ACC_PRIVATE); }
@Override
public boolean isProtected() { return is(ACC_PROTECTED); }
@Override
public boolean isAbstract() { return is(ACC_ABSTRACT); }
@Override
public boolean isFinal() { return is(ACC_FINAL); }
@Override
public boolean isSynthetic() { return is(ACC_SYNTHETIC); }
@Override
public boolean isStatic() { return is(ACC_STATIC); }
@Override
public boolean isInterface() { return is(ACC_INTERFACE); }
@Override
public boolean isSuper() { return is(ACC_SUPER); }
@Override
public boolean isNative() { return is(ACC_NATIVE); }
@Override
public boolean isDeprecated() { return is(ACC_DEPRECATED); }
@Override
public boolean isSynchronized() { return is(ACC_SYNCHRONIZED); }
@Override
public boolean isVolatile() { return is(ACC_VOLATILE); }
@Override
public boolean isBridge() { return is(ACC_BRIDGE); }
@Override
public boolean isVarargs() { return is(ACC_VARARGS); }
@Override
public boolean isTransient() { return is(ACC_TRANSIENT); }
@Override
public boolean isStrict() { return is(ACC_STRICT); }
@Override
public boolean isAnnotation() { return is(ACC_ANNOTATION); }
@Override
public boolean isEnum() { return is(ACC_ENUM); }
public static final int ACCESS_MASK = ACC_PUBLIC | ACC_PRIVATE | ACC_PROTECTED | ACC_FINAL | ACC_STATIC | ACC_SYNCHRONIZED
| ACC_VOLATILE | ACC_BRIDGE | ACC_VARARGS | ACC_TRANSIENT | ACC_NATIVE | ACC_ABSTRACT | ACC_INTERFACE
| ACC_STRICT | ACC_ANNOTATION | ACC_ENUM | ACC_SYNTHETIC | ACC_SUPER | ACC_DEPRECATED;
public static ASMModifiers parse(String[] modifiers) {
int access = 0;
for (String flag : modifiers) {
if (flag.contains(XmlNames.A_PUBLIC)) access |= ACC_PUBLIC;
if (flag.contains(XmlNames.A_PRIVATE)) access |= ACC_PRIVATE;
if (flag.contains(XmlNames.A_PROTECTED)) access |= ACC_PROTECTED;
if (flag.contains(XmlNames.A_STATIC)) access |= ACC_STATIC;
if (flag.contains(XmlNames.A_FINAL)) access |= ACC_FINAL;
if (flag.contains(XmlNames.A_VOLATILE)) access |= ACC_VOLATILE;
if (flag.contains(XmlNames.A_BRIDGE)) access |= ACC_BRIDGE;
if (flag.contains(XmlNames.A_VARARGS)) access |= ACC_VARARGS;
if (flag.contains(XmlNames.A_TRANSIENT)) access |= ACC_TRANSIENT;
if (flag.contains(XmlNames.A_NATIVE)) access |= ACC_NATIVE;
if (flag.contains(XmlNames.A_INTERFACE) || flag.contains(XmlNames.A_DEFENDER_METH)) access |= ACC_INTERFACE;
if (flag.contains(XmlNames.A_ABSTRACT)) access |= ACC_ABSTRACT;
if (flag.contains(XmlNames.A_STRICT)) access |= ACC_STRICT;
if (flag.contains(XmlNames.A_ANNOTATION)) access |= ACC_ANNOTATION;
if (flag.contains(XmlNames.A_ENUM)) access |= ACC_ENUM;
if (flag.contains(XmlNames.A_SYNTHETIC)) access |= ACC_SYNTHETIC;
if (flag.contains(XmlNames.A_SYNCHRONIZED)) access |= ACC_SYNCHRONIZED;
}
return new ASMModifiers(access);
}
}
| 4,956 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
SavePointsMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/SavePointsMethodAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.MethodVisitor;
import static org.objectweb.asm.Opcodes.*;
/**
* This class could be used to insert invocation of
* com.sun.tdk.jcov.runtime.Collect.saveResults() into method.
*
*
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public class SavePointsMethodAdapter extends MethodVisitor {
private final boolean isBegin;
public SavePointsMethodAdapter(final MethodVisitor mv, boolean isBegin) {
super(ASMUtils.ASM_API_VERSION, mv);
this.isBegin = isBegin;
}
@Override
public void visitCode() {
if (isBegin) {
mv.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/runtime/Collect", "saveResults", "()V", false);
}
super.visitCode();
}
@Override
public void visitInsn(int opcode) {
if (!isBegin) {
switch (opcode) {
case ATHROW:
case RET:
case IRETURN:
case LRETURN:
case FRETURN:
case DRETURN:
case ARETURN:
case RETURN:
mv.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/runtime/Collect", "saveResults", "()V", false);
break;
default:
break;
}
}
super.visitInsn(opcode);
}
}
| 2,648 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ASMInstrumentationPlugin.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/ASMInstrumentationPlugin.java | /*
* Copyright (c) 2021, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.InstrumentationPlugin;
import org.objectweb.asm.MethodVisitor;
/**
* SPI class which allows to do additional instrumentation, in addition to instrumentation performed by JCov by default.
* @author Alexander (Shura) Ilin.
*/
public interface ASMInstrumentationPlugin extends InstrumentationPlugin {
/**
* Supplies a MethodVisitor to perform additional instrumentation.
* @return A valid method visitor. If no instrumentation needed, must return <code>visitor</code> argument.
*/
MethodVisitor methodVisitor(int access, String owner, String name, String desc, MethodVisitor visitor);
}
| 1,900 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
BranchCodeMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/BranchCodeMethodAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.BasicBlock;
import java.util.*;
import static org.objectweb.asm.Opcodes.*;
import com.sun.tdk.jcov.instrument.CharacterRangeTable;
import com.sun.tdk.jcov.instrument.Constants;
import com.sun.tdk.jcov.instrument.DataBlock;
import com.sun.tdk.jcov.instrument.DataBlockCatch;
import com.sun.tdk.jcov.instrument.DataBlockFallThrough;
import com.sun.tdk.jcov.instrument.DataBlockMethEnter;
import com.sun.tdk.jcov.instrument.DataBlockTarget;
import com.sun.tdk.jcov.instrument.DataBlockTargetCase;
import com.sun.tdk.jcov.instrument.DataBlockTargetCond;
import com.sun.tdk.jcov.instrument.DataBlockTargetDefault;
import com.sun.tdk.jcov.instrument.DataBlockTargetGoto;
import com.sun.tdk.jcov.instrument.DataBranchCond;
import com.sun.tdk.jcov.instrument.DataBranchGoto;
import com.sun.tdk.jcov.instrument.DataBranchSwitch;
import com.sun.tdk.jcov.instrument.DataExit;
import com.sun.tdk.jcov.instrument.DataExitSimple;
import com.sun.tdk.jcov.instrument.DataMethodWithBlocks;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.tree.*;
import static org.objectweb.asm.tree.AbstractInsnNode.*;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
class BranchCodeMethodAdapter extends OffsetRecordingMethodAdapter {
private final MethodVisitor nextVisitor;
private final List<DataExit> exits;
private final List<DataBlock> src;
private final Map<AbstractInsnNode, BasicBlock> insnToBB;
private final InstrumentationParams params;
private final Map<DataBlock, LabelNode> blockLabels;
public BranchCodeMethodAdapter(final MethodVisitor mv,
final DataMethodWithBlocks method, InstrumentationParams params) {
super(new MethodNode(method.getAccess(), method.getName(), method.getVmSignature(), method.getSignature(), method.getExceptions()),
method);
this.nextVisitor = mv;
this.insnToBB = new IdentityHashMap<AbstractInsnNode, BasicBlock>();
this.exits = new ArrayList<DataExit>();
this.src = new ArrayList<DataBlock>();
this.params = params;
blockLabels = new IdentityHashMap<>();
}
private BasicBlock getBB(AbstractInsnNode insn, int startBCI) {
BasicBlock bb = insnToBB.get(insn);
if (bb == null) {
bb = new BasicBlock(method.rootId(), startBCI);
insnToBB.put(insn, bb);
} else if (startBCI >= 0) {
bb.setStartBCI(startBCI);
}
return bb;
}
private BasicBlock getBB(AbstractInsnNode insn) {
return getBB(insn, -1);
}
private AbstractInsnNode peek(ListIterator iit) {
// Do a next() to get the next instruction..
// Then immediately do a previous to restore our position.
if (iit.hasNext()) {
AbstractInsnNode insn = (AbstractInsnNode) iit.next();
iit.previous();
return insn;
}
return null;
}
/**
* Do fix ups so that: There are unique CodeLabelNodes at the beginning of
* each basic block; All branch-mode blocks hang off CodeLabelNodes Misc
* info, like case values, are attached Fall throughs from one block to
* another are computed
*
*/
private BasicBlock[] completeComputationOfCodeLabelNodes() {
MethodNode methodNode = (MethodNode) mv;
InsnList instructions = methodNode.instructions;
int[] allToReal = new int[instructions.size()];
int allIdx = 0;
int insnIdx = 0;
ListIterator iit = instructions.iterator();
// Create the method entry block and basic block
AbstractInsnNode insnFirst = peek(iit);
BasicBlock bbFirst = getBB(insnFirst, 0);
DataBlock blockFirst = new DataBlockMethEnter(bbFirst.rootId());
bbFirst.add(blockFirst);
while (iit.hasNext()) {
AbstractInsnNode insn = (AbstractInsnNode) iit.next();
allToReal[allIdx++] = insnIdx;
int bci = bcis[insnIdx];
int opcode = insn.getOpcode();
if (opcode < 0) {
// a pseudo-instruction
if (insn.getType() == AbstractInsnNode.LINE) {
LineNumberNode lineNode = (LineNumberNode) insn;
method().addLineEntry(bci, lineNode.line);
}
} else {
// a real instruction
++insnIdx; // advance the real instruction index
//System.out.println( "#" + (insnIdx - 1) +
// " bci: " + bci + " " +
// instr.toString().replace("org.objectweb.asm.tree.", "").replace("@", " @ ") +
// " [" + (opcode>=0? Constants.opcNames[opcode] : " pseudo") +"]");
switch (opcode) {
case IFEQ:
case IFNE:
case IFLT:
case IFGE:
case IFGT:
case IFLE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPGE:
case IF_ICMPGT:
case IF_ICMPLE:
case IF_ACMPEQ:
case IF_ACMPNE:
case IFNULL:
case IFNONNULL: //case JSR:
{
JumpInsnNode jumpInsn = (JumpInsnNode) insn;
LabelNode insnTrue = jumpInsn.label;
int bciFalse = bcis[insnIdx]; // fall-through
DataBranchCond branch = new DataBranchCond(method.rootId(), bci, bciFalse - 1);
DataBlockTarget blockTrue = new DataBlockTargetCond(branch.rootId(), true);
DataBlockTarget blockFalse = new DataBlockTargetCond(branch.rootId(), false);
branch.addTarget(blockTrue);
branch.addTarget(blockFalse);
AbstractInsnNode insnFalse = peek(iit);
assert (insnFalse != null); // must be fall-through code
BasicBlock bbTrue = getBB(insnTrue);
BasicBlock bbFalse = getBB(insnFalse, bciFalse);
exits.add(branch);
// assign a new label for branch counting
LabelNode nlab = new LabelNode();
jumpInsn.label = nlab; // branch to new label
bbTrue.add(blockTrue);
blockLabels.put(blockTrue, nlab);
bbFalse.add(blockFalse);
break;
}
case TABLESWITCH: {
TableSwitchInsnNode switchInsn = (TableSwitchInsnNode) insn;
// Create a block and basic-block the "default:" case
LabelNode insnDflt = switchInsn.dflt;
BasicBlock bbDefault = getBB(insnDflt);
DataBlockTargetDefault blockDefault = new DataBlockTargetDefault(bbDefault.rootId());
// assign a new default label for branch counting
LabelNode nlab = new LabelNode();
switchInsn.dflt = nlab; // branch to new label
bbDefault.add(blockDefault);
blockLabels.put(blockDefault, nlab);
// Create the branch information
int bciEnd = bcis[insnIdx] - 1; // end of the switch
DataBranchSwitch branch = new DataBranchSwitch(method.rootId(), bci, bciEnd, blockDefault);
branch.addTarget(blockDefault);
exits.add(branch);
// Process the other cases
ListIterator lit = switchInsn.labels.listIterator();
int key = switchInsn.min;
while (lit.hasNext()) {
// Create a block and basic-block the case
LabelNode labCase = (LabelNode) lit.next();
BasicBlock bbCase = getBB(labCase);
DataBlockTargetCase blockCase = new DataBlockTargetCase(bbCase.rootId(), key++);
branch.addTarget(blockCase);
// assign a new label to the case for branch counting
nlab = new LabelNode();
lit.set(nlab);
bbCase.add(blockCase);
blockLabels.put(blockCase, nlab);
}
break;
}
case LOOKUPSWITCH: {
LookupSwitchInsnNode switchInsn = (LookupSwitchInsnNode) insn;
// Create a block and basic-block the "default:" case
LabelNode insnDflt = switchInsn.dflt;
BasicBlock bbDefault = getBB(insnDflt);
DataBlockTargetDefault blockDefault = new DataBlockTargetDefault(bbDefault.rootId());
// assign a new default label for branch counting
LabelNode nlab = new LabelNode();
switchInsn.dflt = nlab; // branch to new label
bbDefault.add(blockDefault);
blockLabels.put(blockDefault, nlab);
// Create the branch information
int bciEnd = bcis[insnIdx] - 1; // end of the switch
DataBranchSwitch branch = new DataBranchSwitch(method.rootId(), bci, bciEnd, blockDefault);
branch.addTarget(blockDefault);
exits.add(branch);
// Process the other cases
ListIterator kit = switchInsn.keys.listIterator();
ListIterator lit = switchInsn.labels.listIterator();
while (lit.hasNext()) {
// Create a block and basic-block the case
LabelNode labCase = (LabelNode) lit.next();
BasicBlock bbCase = getBB(labCase);
Integer key = (Integer) kit.next();
DataBlockTargetCase blockCase = new DataBlockTargetCase(branch.rootId(), key.intValue());
branch.addTarget(blockCase);
// assign a new label to the case for branch counting
nlab = new LabelNode();
lit.set(nlab);
bbCase.add(blockCase);
blockLabels.put(blockCase, nlab);
}
break;
}
case GOTO: {
JumpInsnNode jumpInsn = (JumpInsnNode) insn;
// Create origin info, a branch
int bciEnd = bcis[insnIdx] - 1;
DataBranchGoto branch = new DataBranchGoto(method.rootId(), bci, bciEnd);
exits.add(branch);
// Create destination info, a block target
LabelNode insnTarget = jumpInsn.label;
BasicBlock bbTarget = getBB(insnTarget);
DataBlockTarget blockTarget = new DataBlockTargetGoto(bbTarget.rootId());
branch.addTarget(blockTarget);
// assign a new label for branch counting
LabelNode nlab = new LabelNode();
jumpInsn.label = nlab; // branch to new label
bbTarget.add(blockTarget);
blockLabels.put(blockTarget, nlab);
break;
}
case ATHROW:
case RET:
case IRETURN:
case LRETURN:
case FRETURN:
case DRETURN:
case ARETURN:
case RETURN: {
int bciNext = bcis[insnIdx];
DataExit exit = new DataExitSimple(method.rootId(), bci, bciNext - 1, insn.getOpcode());
exits.add(exit);
AbstractInsnNode insnNext = peek(iit);
if (insnNext != null) {
// If there is code after this, it has to be the start of a
// new basic block
getBB(insnNext, bciNext);
}
break;
}
default:
break;
}
// try add src block
}
}
// Now go through the try-catch blocks
LabelNode previousHandler = null;
for (Iterator tbit = methodNode.tryCatchBlocks.iterator(); tbit.hasNext();) {
TryCatchBlockNode tcbn = (TryCatchBlockNode) tbit.next();
LabelNode insnHandler = tcbn.handler;
if (insnHandler != previousHandler) {
previousHandler = insnHandler;
// Create destination info, a block target
BasicBlock bbCatch = getBB(insnHandler);
DataBlockCatch blockCatch = new DataBlockCatch(bbCatch.rootId());
// assign a new label for catch counting
LabelNode nlab = new LabelNode();
tcbn.handler = nlab; // change handler
bbCatch.add(blockCatch);
blockLabels.put(blockCatch, nlab);
}
}
if (method().getCharacterRangeTable() != null) {
boolean newBlock = true;
int skip = 0;
iit = instructions.iterator();
while (iit.hasNext()) {
AbstractInsnNode insn = (AbstractInsnNode) iit.next();
int index = instructions.indexOf(insn);
int bci = bcis[allToReal[index]];
if (bci == skip) {
continue;
}
if (insnToBB.get(insn) != null) {
skip = bcis[allToReal[ instructions.indexOf(insn)]];
}
if (insn.getOpcode() < 0) {
continue;
}
for (CharacterRangeTable.CRTEntry entry : method().getCharacterRangeTable().getEntries()) {
if (entry.startBCI() == bci) {
if ((entry.flags & CharacterRangeTable.CRTEntry.CRT_STATEMENT) != 0 /*& newBlock*/) {
newBlock = false;
if (insnToBB.get(insn) == null) {
//System.out.println("Should add block at: " + bci + " in " + method().name +
// " for " + Constants.opcNames[insn.getOpcode()]);
getBB(insn);
break;
}
}
} else {
if (entry.endBCI() == index && (entry.flags & CharacterRangeTable.CRTEntry.CRT_FLOW_TARGET) != 0) {
newBlock = true;
}
}
}
}
}
// Compute the startBCI for any basic blocks that don't have it'
BasicBlock[] basicBlocks = new BasicBlock[insnToBB.size()];
int i = 0;
for (Map.Entry<AbstractInsnNode, BasicBlock> entry : insnToBB.entrySet()) {
BasicBlock bb = entry.getValue();
if (bb.startBCI() < 0) {
AbstractInsnNode insn = entry.getKey();
int index = instructions.indexOf(insn);
int bci = bcis[allToReal[index]];
bb.setStartBCI(bci);
}
basicBlocks[i++] = bb;
}
Arrays.sort(basicBlocks);
return basicBlocks;
}
/**
* Compute end BCIs for basic blocks, then set this info into detail blocks.
* Assumes the basic blocks are sorted
*/
private void computeEndBCIsAndFoldInExits(BasicBlock[] basicBlocks) {
int ei = 0; // exit index
BasicBlock prev = basicBlocks[0];
for (int bi = 1; bi <= basicBlocks.length; ++bi) {
BasicBlock curr = null;
int start;
if (bi == basicBlocks.length) {
start = method().getBytecodeLength();
} else {
curr = basicBlocks[bi];
start = curr.startBCI();
}
int prevStart = prev.startBCI();
// Set the previous block to end just before the current starts
int prevEnd = start - 1;
prev.setEndBCI(prevEnd);
// Now that we know the endBCI, we can determine if
// any exits reside in this range
DataExit exit = null;
int exitStart;
if (ei < exits.size()) {
exit = exits.get(ei);
exitStart = exit.startBCI();
} else {
exitStart = -1; // always go to the fall-into code
}
if (exitStart >= prevStart && exitStart <= prevEnd) {
// The exit is in the prev block attach it
prev.setExit(exit);
// System.out.println("found " + ei + " BB: " + prev + " exit: " + exit);
++ei; // set-up to handle the next exit
} else {
// There is no exit from the prev block, so we fall
// into the curr block (if any)
if (curr != null) {
DataBlock fall = new DataBlockFallThrough(curr.rootId());
curr.add(fall);
}
}
prev = curr;
}
// System.out.println("ei: " + ei + " / " + exits.size());
assert (ei == exits.size());
}
private void insertInstrumentation() {
MethodNode methodNode = (MethodNode) mv;
InsnList instructions = methodNode.instructions;
for (Map.Entry<AbstractInsnNode, BasicBlock> entry : insnToBB.entrySet()) {
// Basic block 'bb' starts at instruction 'insn'
AbstractInsnNode insn = entry.getKey();
BasicBlock bb = entry.getValue();
// Get the entry blocks for this basic block
Collection<DataBlock> blocks = bb.blocks();
int remaining = blocks.size();
LabelNode realStuff = null;
if (remaining > 1) {
// There are two or more entries to this block.
// We will need a label to jump over the other entries.
realStuff = new LabelNode();
}
// any fallen into entry blocks must be instrumented first (no label
// switching was done for them.
DataBlock fallenInto = bb.fallenInto();
if (fallenInto != null) {
assert (blockLabels.get(fallenInto) == null);
instructions.insertBefore(insn, Instrumenter.instrumentation(fallenInto, params.isDetectInternal()));
if (--remaining > 0) {
// jump over the next instrumentation of this basic block
instructions.insertBefore(insn, new JumpInsnNode(GOTO, realStuff));
}
}
// Process the other entry blocks
for (DataBlock block : blocks) {
if (!block.isFallenInto()) {
// insert the label
LabelNode lnode = blockLabels.get(block);
assert (lnode != null);
// insert created label
instructions.insertBefore(insn, lnode);
// insert the instrumentation
instructions.insertBefore(insn, Instrumenter.instrumentation(block, params.isDetectInternal()));
if (--remaining > 0) {
// jump over the next instrumentation of this basic block
instructions.insertBefore(insn, new JumpInsnNode(GOTO, realStuff));
}
}
}
if (realStuff != null) {
// insert label for the real code
instructions.insertBefore(insn, realStuff);
}
assert (remaining == 0);
}
}
@Override
public void visitAttribute(Attribute attr) {
super.visitAttribute(attr);
if (attr instanceof CharacterRangeTableAttribute) {
method().setCharacterRangeTable(((CharacterRangeTableAttribute) attr).getCrt());
}
}
// the instruction list has been built, insert the instrumentation
@Override
public void visitEnd() {
super.visitEnd();
BasicBlock[] basicBlocks = completeComputationOfCodeLabelNodes();
computeEndBCIsAndFoldInExits(basicBlocks);
//debugDump();
insertInstrumentation();
method().setBasicBlocks(basicBlocks);
// push the result to the writer
MethodNode methodNode = (MethodNode) mv;
methodNode.accept(nextVisitor);
}
private void debugDump() {
/* Opcode Names */
MethodNode methodNode = (MethodNode) mv;
InsnList instructions = methodNode.instructions;
ListIterator iit = instructions.iterator();
System.out.println(methodNode.name + " ----");
while (iit.hasNext()) {
AbstractInsnNode instr = (AbstractInsnNode) iit.next();
int opcode = instr.getOpcode();
if (opcode >= 0) {
System.out.print(" ");
System.out.print(Constants.opcNames[opcode]);
System.out.print(" ");
}
switch (instr.getType()) {
case LINE:
System.out.print(((LineNumberNode) instr).line);
System.out.print("#");
break;
case LABEL:
System.out.print(labelString(((LabelNode) instr)));
System.out.print(":");
break;
case FRAME:
System.out.print("frame-");
break;
case JUMP_INSN:
System.out.print(labelString(((JumpInsnNode) instr).label));
break;
case LOOKUPSWITCH: {
LookupSwitchInsnNode node = (LookupSwitchInsnNode) instr;
System.out.println();
System.out.print(" default: ");
System.out.print(labelString(node.dflt));
int len = node.labels.size();
for (int i = 0; i < len; ++i) {
LabelNode lnode = (LabelNode) (node.labels.get(i));
Integer key = (Integer) (node.keys.get(i));
System.out.println();
System.out.print(" ");
System.out.print(key);
System.out.print(": ");
System.out.print(labelString(lnode));
}
break;
}
case TABLESWITCH_INSN: {
TableSwitchInsnNode node = (TableSwitchInsnNode) instr;
System.out.println();
System.out.print(" default: ");
System.out.print(labelString(node.dflt));
int len = node.labels.size();
int key = node.min;
for (int i = 0; i < len; ++i) {
LabelNode lnode = (LabelNode) (node.labels.get(i));
System.out.println();
System.out.print(" ");
System.out.print(key++);
System.out.print(": ");
System.out.print(labelString(lnode));
}
break;
}
default:
break;
}
if (insnToBB.get(instr) != null) {
System.out.println(" block [" + insnToBB.get(instr).startBCI()
+ ", " + insnToBB.get(instr).endBCI() + "]");
} else {
System.out.println();
}
}
}
private String labelString(LabelNode lnode) {
Label lab = lnode.getLabel();
return lab.toString();
}
}
| 26,325 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
InstrumentedAttributeClassAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/InstrumentedAttributeClassAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ByteVector;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public class InstrumentedAttributeClassAdapter extends ClassVisitor {
private boolean isAlreadyInstrumented = false;
public boolean isAlreadyInstrumented() {
return isAlreadyInstrumented;
}
public InstrumentedAttributeClassAdapter(final ClassVisitor cv) {
super(ASMUtils.ASM_API_VERSION, cv);
}
public void visitAttribute(Attribute attr) {
System.out.println(attr.type);
if (attr.type.equals(AttributeInstrumented.INSTRUMENTED)) {
System.out.println("class is already instrumented");
isAlreadyInstrumented = true;
}
super.visitAttribute(attr);
}
@Override
public void visitEnd() {
if (!isAlreadyInstrumented) {
super.visitAttribute(new AttributeInstrumented());
}
super.visitEnd();
}
private static class AttributeInstrumented extends Attribute {
final static String INSTRUMENTED = "Instrumented";
AttributeInstrumented() {
super(INSTRUMENTED);
}
protected Attribute read(
final ClassReader cr,
final int off,
final int len,
final char[] buf,
final int codeOff,
final Label[] labels) {
return new AttributeInstrumented();
}
protected ByteVector write(
final ClassWriter cw,
final byte[] code,
final int len,
final int maxStack,
final int maxLocals) {
return new ByteVector().putShort(cw.newUTF8(INSTRUMENTED));
}
}
}
| 3,228 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
InvokeMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/InvokeMethodAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import com.sun.tdk.jcov.instrument.DataAbstract;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import static org.objectweb.asm.Opcodes.*;
/**
* @author Leonid Mesnik
* @author Sergey Borodin
*
* Used in dynamic instrumentation mode. It handles method invocations - sets
* instructions to serve caller include options (setExpected[Refl] instructions)
* and checks all virtual invocations. In contrast to StaticInvokeMethodAdapter,
* it hits CollectDetect slots and does it for all such invocations, not
* filtering abstract and native invocations (we do not see access flags in
* meth. invoke instruction)
*
*/
public class InvokeMethodAdapter extends MethodVisitor {
private final String className;
private final InstrumentationParams params;
public InvokeMethodAdapter(MethodVisitor mv, String className, final InstrumentationParams params) {
super(ASMUtils.ASM_API_VERSION, mv);
this.className = className;
this.params = params;
}
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
if ((opcode == GETFIELD || opcode == GETSTATIC)
&& params.isInstrumentFields() && params.isIncluded(owner)
&& params.isCallerFilterAccept(className)) {
InsnList il = new InsnList();
il.add(new LdcInsnNode(DataAbstract.getInvokeID(owner, name, desc)));
il.add(new MethodInsnNode(INVOKESTATIC, "com/sun/tdk/jcov/runtime/CollectDetect", "invokeHit", "(I)V", false));
il.accept(this);
}
super.visitFieldInsn(opcode, owner, name, desc);
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
if (params.isCallerFilterOn()
&& params.isCallerFilterAccept(className)) {
if (ReflPair.contains(owner, name)) {
//handle reflection invokations
visitReflectionCI(ReflPair.valueOf(owner, name));
} else {
int id = (name + desc).hashCode();
super.visitLdcInsn(id);
super.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/runtime/CollectDetect", "setExpected", "(I)V", false);
}
}
if ((opcode == INVOKEVIRTUAL || opcode == INVOKEINTERFACE)
&& params.isInstrumentAbstract()
&& params.isIncluded(owner)
&& params.isCallerFilterAccept(className)) {
super.visitLdcInsn(DataAbstract.getInvokeID(owner, name, desc));
super.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/runtime/CollectDetect", "invokeHit", "(I)V", false);
}
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
private enum ReflPair {
CLASS("java/lang/Class", "newInstance"),
METHOD("java/lang/reflect/Method", "invoke"),
CONSTRUCTOR("java/lang/reflect/Constructor", "newInstance");
private String className;
private String methName;
ReflPair(String className, String methName) {
this.className = className;
this.methName = methName;
}
private boolean isEqual(String clName, String mName) {
return className.equals(clName) && methName.equals(mName);
}
public static boolean contains(String clName, String mName) {
return valueOf(clName, mName) != null;
}
public static ReflPair valueOf(String clName, String mName) {
for (ReflPair p : values()) {
if (p.isEqual(clName, mName)) {
return p;
}
}
return null;
}
}
private void visitReflectionCI(ReflPair p) {
if (p == null) {
return;
}
switch (p) {
case CLASS:
super.visitInsn(DUP);
super.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/instrument/InvokeMethodAdapter",
"getMethodHash", "(Ljava/lang/Object;)I", false);
super.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/runtime/CollectDetect",
"setExpectedFull", "(I)V", false);
break;
case METHOD:
super.visitInsn(DUP2_X1);
super.visitInsn(POP);
super.visitInsn(POP);
super.visitInsn(DUP);
super.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/instrument/InvokeMethodAdapter",
"getMethodHash", "(Ljava/lang/Object;)I", false);
super.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/runtime/CollectDetect",
"setExpectedFull", "(I)V", false);
super.visitInsn(DUP_X2);
super.visitInsn(POP);
break;
case CONSTRUCTOR:
super.visitInsn(DUP2);
super.visitInsn(POP);
super.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/instrument/InvokeMethodAdapter",
"getMethodHash", "(Ljava/lang/Object;)I", false);
super.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/runtime/CollectDetect",
"setExpectedFull", "(I)V", false);
break;
default:
break;
}
}
public static int getMethodHash(Object obj) {
String desc = "";
if (obj instanceof Method) {
Method m = (Method) obj;
Class c = m.getDeclaringClass();
desc = c.getName().replace(".", "/");
desc += m.getName();
Class[] types = m.getParameterTypes();
desc += "(";
for (Class t : types) {
desc += vmType(t.getName());
}
desc += ")";
desc += vmType(m.getReturnType().getName());
} else if (obj instanceof Constructor) {
Constructor c = (Constructor) obj;
Class cl = c.getDeclaringClass();
desc = cl.getName().replace(".", "/");
desc += "<init>";
Class[] types = c.getParameterTypes();
desc += "(";
for (Class t : types) {
desc += vmType(t.getName());
}
desc += ")";
desc += "V";
} else if (obj instanceof Class) {
Class c = (Class) obj;
desc = c.getName().replace(".", "/");
desc += "<init>" + "()V";
}
return desc.hashCode();
}
private static String vmType(String type) {
// [<s> -> <s>[] <s> is converted recursively
// L<s>; -> <s> characters '/' are replaced by '.' in <s>
// B -> byte
// C -> char
// D -> double
// F -> float
// I -> int
// J -> long
// S -> short
// Z -> boolean
// V -> void valid only in method return type
String res = "";
if (type.equals("")) {
return "V";
}
while (type.endsWith("[]")) {
type = type.substring(0, type.length() - 2);
res += "[";
}
while (type.startsWith("[")) {
res += '[';
type = type.substring(1);
}
if (type.equals("byte")) {
res += "B";
} else if (type.equals("char")) {
res += "C";
} else if (type.equals("double")) {
res += "D";
} else if (type.equals("float")) {
res += "F";
} else if (type.equals("int")) {
res += "I";
} else if (type.equals("long")) {
res += "J";
} else if (type.equals("short")) {
res += "S";
} else if (type.equals("boolean")) {
res += "Z";
} else if (type.equals("void")) {
res += "V";
} else {
type = type.replace(".", "/");
if (!type.startsWith("L")) {
type = "L" + type;
}
res += type;
if (!type.endsWith(";")) {
res += ";";
}
}
return res;
}
}
| 9,826 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ASMUtils.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/ASMUtils.java | /*
* Copyright (c) 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import org.objectweb.asm.Opcodes;
public class ASMUtils {
/**
* The ASM API version that should be used by jcov.
*/
public static final int ASM_API_VERSION = Opcodes.ASM9;
}
| 1,442 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ClassMorph.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/ClassMorph.java | /*
* Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.data.FileFormatException;
import com.sun.tdk.jcov.instrument.BasicBlock;
import com.sun.tdk.jcov.instrument.CharacterRangeTable;
import com.sun.tdk.jcov.instrument.DataBlock;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.instrument.DataMethod;
import com.sun.tdk.jcov.instrument.DataMethodEntryOnly;
import com.sun.tdk.jcov.instrument.DataMethodInvoked;
import com.sun.tdk.jcov.instrument.DataMethodWithBlocks;
import com.sun.tdk.jcov.instrument.DataPackage;
import com.sun.tdk.jcov.instrument.DataRoot;
import com.sun.tdk.jcov.instrument.InstrumentationOptions;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import com.sun.tdk.jcov.instrument.XmlNames;
import com.sun.tdk.jcov.io.Reader;
import com.sun.tdk.jcov.runtime.Collect;
import com.sun.tdk.jcov.runtime.FileSaver;
import com.sun.tdk.jcov.tools.OptionDescr;
import com.sun.tdk.jcov.util.DebugUtils;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.ModuleVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.util.TraceClassVisitor;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Adler32;
import static java.lang.String.format;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public class ClassMorph {
private DataRoot root;
private final String outputFile;
private HashMap<String, Long> instrumented = new HashMap<String, Long>(); // Set should work better
private HashMap<String, byte[]> instrumentedValues = new HashMap<String, byte[]>(); // Set should work better
private static final boolean IS_SELFTEST = System.getProperty("jcov.selftest") != null;
private final InstrumentationParams params;
private boolean rtClassesInstrumented = false;
private static final Logger logger;
private String currentModuleName = null;
static {
Utils.initLogger();
logger = Logger.getLogger(ClassMorph.class.getName());
}
//For Agent
public ClassMorph(String filename, DataRoot root, final InstrumentationParams params) {
this.outputFile = filename;
this.root = root;
this.params = params; // can't use params from root - they can be different from instrumenting ones (? - but not at the moment)
rtClassesInstrumented = params.isDataSaveSpecified();
findAlreadyInstrumentedAndSetID();
}
public DataRoot getRoot(){
return root;
}
/**
* Default constructor for Instr and TemplGen. Uses specified template as
* output file.
*/
public ClassMorph(final InstrumentationParams params, String template) {
this(template, new DataRoot(params), params);
this.root.getXMLHeadProperties().put("os.name", System.getProperty("os.name"));
this.root.getXMLHeadProperties().put("os.arch", System.getProperty("os.arch"));
this.root.getXMLHeadProperties().put("os.version", System.getProperty("os.version"));
this.root.getXMLHeadProperties().put("user.name", System.getProperty("user.name"));
this.root.getXMLHeadProperties().put("java.version", System.getProperty("java.version"));
this.root.getXMLHeadProperties().put("java.runtime.version", System.getProperty("java.runtime.version"));
}
public boolean isTransformable(String className) {
if (className.equals("java/lang/Object") && !params.isDynamicCollect() && params.isIncluded(className)) {
logger.log(Level.WARNING, "java.lang.Object can't be statically instrumented and was excluded");
return false;
}
if (className.startsWith("com/sun/tdk/jcov") && !IS_SELFTEST || className.startsWith("org/objectweb/asm")) {
logger.log(Level.INFO, format("%s - skipped (should not perform self-instrument)", className));
return false;
}
if (className.startsWith("sun/reflect/Generated")) {
logger.log(Level.WARNING, format("%s - skipped (should not instrument generated classes)", className));
return false;
}
return true;
}
public boolean isAlreadyTransformed(String className) {
return instrumented.containsKey(className);
}
public boolean shouldTransform(String className) {
return isTransformable(className)
&& !isAlreadyTransformed(className)
&& params.isIncluded(className);
}
/**
* <p> Instrument loaded class data. </p>
*
* @param classfileBuffer Class data
* @param loader ClassLoader containing this class (used in agent)
* @param flushPath
* @return
* @throws IOException
*/
public byte[] morph(byte[] classfileBuffer, ClassLoader loader, String flushPath) throws IOException {
if (loader == null) {
loader = ClassLoader.getSystemClassLoader();
}
if (classfileBuffer[0] != -54 || classfileBuffer[1] != -2 || classfileBuffer[2] != -70 || classfileBuffer[3] != -66) {
throw new IOException("Corrupted class file (0xCAFEBABE header not found)");
}
OffsetLabelingClassReader cr = new OffsetLabelingClassReader(classfileBuffer);
String fullname = cr.getClassName();
if (!isTransformable(fullname)) {
return null;
}
boolean shouldFlush = (flushPath != null);
if (isAlreadyTransformed(fullname)) {
long cs = computeCheckSum(classfileBuffer);
Long oldCs = instrumented.get(fullname);
if (oldCs > 0) {
if (cs == oldCs && flushPath != null) { // the same class - restore from flushed
logger.log(Level.FINE, "{0} - instrumented copy used", fullname);
return DebugUtils.readClass(fullname, flushPath);
} else {
logger.log(Level.WARNING, "application has different classes with the same name: {0}", fullname);
}
}
}
if (params.isClassesReload()
&& !shouldTransform(fullname)
&& isAlreadyTransformed(fullname)
&& params.isDynamicCollect()) {
return instrumentedValues.get(fullname);
}
if (!shouldTransform(fullname)) {
if (!params.isDynamicCollect() || // isStatic
!params.isCallerFilterOn() && !params.isInstrumentFields()) {
if (isAlreadyTransformed(fullname)) {
logger.log(Level.INFO, "{0} - skipped (already instrumented)", fullname);
}
if (!params.isIncluded(fullname)) {
logger.log(Level.INFO, "{0} - skipped (is not included or is excluded explicitly)", fullname);
}
//null tells to AbstractUniversalInstrumenter not to overwrite existing data
return null;
}
// support of caller_include feature
// even those classes which are out of scope require some minor
// transformation
ClassWriter cw = new OverriddenClassWriter(cr, ClassWriter.COMPUTE_MAXS, loader);
ClassVisitor cv = shouldFlush ? new TraceClassVisitor(cw, DebugUtils.getPrintWriter(fullname, flushPath))
: cw;
cv = new InvokeClassAdapter(cv, params);
cr.accept(cv, 0);
byte[] res = cw.toByteArray();
if (shouldFlush) {
DebugUtils.flushInstrumentedClass(flushPath, fullname, res);
}
if (!params.isDynamicCollect() && !rtClassesInstrumented && isPreVMLoadClass(fullname)) {
rtClassesInstrumented = true;
logger.log(Level.WARNING, "It's possible that you are instrumenting classes which are loaded before VM is loaded.\n" +
"It's recommended to add saveAtEnd at java/lang/Shutdown.runHooks method. Data could be lost otherwise.");
}
return res;
}
String moduleName = null;
if (params.isDynamicCollect()) {
moduleName = updateClassModule(fullname);
}
else{
if (currentModuleName != null) {
moduleName = "module " + currentModuleName;
}
}
if (moduleName == null){
moduleName = "module "+ XmlNames.NO_MODULE;
}
if (!params.isModuleIncluded(moduleName.substring(7, moduleName.length()))){
return null;
}
// Checksum should be counted before changing content
long checksum = params.isDynamicCollect() ? -1
: computeCheckSum(classfileBuffer);
// The stackmap should be calculated only when static instrumentation
// is used and class version 50. In this case the classfiles should
// be downgraded to v 49.
int opt = ClassWriter.COMPUTE_MAXS;
if (params.isStackMapShouldBeUpdated()) {
if (params.isDynamicCollect() && classfileBuffer[7] == 50) {
classfileBuffer[7] = 49;
}
}
if (classfileBuffer[7] > 49) {
opt = ClassWriter.COMPUTE_FRAMES;
}
ClassWriter cw = new OverriddenClassWriter(cr, opt, loader);
DataClass k = new DataClass(root.rootId(), fullname, moduleName.substring(7), checksum, false);
// ClassVisitor cv = shouldFlush ? new TraceClassVisitor
// (cw, DebugUtils.getPrintWriter(fullname, Options.getFlushPath())) :
// cw;
ClassVisitor cv = cw;
cv = new DeferringMethodClassAdapter(cv, k, params);
cr.accept(cv,
new Attribute[]{new CharacterRangeTableAttribute(new CharacterRangeTable(root.rootId()))}, 0);
if (k.hasModifier(Opcodes.ACC_SYNTHETIC) && !params.isInstrumentSynthetic()) {
return null;
} else {
root.addClass(k);
instrumented.put(fullname, checksum);
instrumentedValues.put(fullname, cw.toByteArray());
byte[] res = cw.toByteArray();
if (shouldFlush) {
DebugUtils.flushInstrumentedClass(flushPath, fullname, res);
}
if (!params.isDynamicCollect() && !rtClassesInstrumented && isPreVMLoadClass(fullname)) {
rtClassesInstrumented = true;
logger.log(Level.WARNING, "It's possible that you are instrumenting classes which are loaded before VM is loaded.\n" +
"It's recommended to add saveatend at java/lang/Shutdown.runHooks method. Data could be lost otherwise.");
}
return res;
}
}
public byte[] clearHashes(byte[] moduleInfo, ClassLoader loader) {
ClassReader cr = new ClassReader(moduleInfo);
ClassWriter cw = new OverriddenClassWriter(cr, ClassWriter.COMPUTE_FRAMES, loader);
cr.accept( new ClassVisitor(ASMUtils.ASM_API_VERSION, cw) {
@Override
public void visitAttribute(final Attribute attribute) {
if (!attribute.type.equals("ModuleHashes")) {
super.visitAttribute(attribute);
}
}
}, 0);
return cw.toByteArray();
}
public byte[] addExports(byte[] moduleInfo, List<String> exports, ClassLoader loader) {
ClassReader cr = new ClassReader(moduleInfo);
ClassWriter cw = new OverriddenClassWriter(cr, ClassWriter.COMPUTE_FRAMES, loader);
cr.accept( new ClassVisitor(ASMUtils.ASM_API_VERSION, cw) {
@Override
public ModuleVisitor visitModule(String name, int access, String version) {
ModuleVisitor mv = super.visitModule(name, access, version);
exports.forEach(e -> {
mv.visitPackage(e);
mv.visitExport(e, 0);
});
return mv;
}
}, 0);
return cw.toByteArray();
}
public void setCurrentModuleName(String name){
currentModuleName = name;
}
private String updateClassModule(String fullname){
if ("java/lang/ClassCircularityError".equals(fullname)){
return "module java.base";
}
String result = null;
try{
if (fullname.contains("$")){
fullname = fullname.substring(0, fullname.indexOf("$"));
}
Class cls = Class.forName(fullname.replaceAll("/","."));
java.lang.reflect.Method getModuleMethod = Class.class.getDeclaredMethod("getModule");
Object module = getModuleMethod.invoke(cls);
result = module.toString();
}catch(Throwable ignore){
}
return result;
}
public static long computeCheckSum(byte[] classfileBuffer) {
// Adler32 adler = new Adler32();
// adler.update(classfileBuffer, 0, classfileBuffer.length);
// long checksum = adler.getValue();
// return checksum;
int i = 0;
i += 4;//skip magic
i += 4;//skip minor/major version
int cp_count = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;//skip constant pool count
// Need to cache UTF8 values and their indexes to be able to resolve
// method and attribute names
// TreeMap<Integer, String> cp_utf8_cache = new TreeMap();
HashMap<Integer, String> cp_utf8_cache = new HashMap(); // faster get
//Process constant pool
for (int j = 0; j < cp_count - 1; j++) {
int cp_type = classfileBuffer[i++];
switch (cp_type) {
case 1://utf8
int utf8_length = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;
// byte[] value = Arrays.copyOfRange(classfileBuffer, i, i + utf8_length);
// byte[] value = new byte[utf8_length];
// System.arraycopy(classfileBuffer, i, value, 0, utf8_length); // jdk1.5 support
// String is immutable. No need to copy arrays
String sval = new String(classfileBuffer, i, utf8_length, Charset.forName("UTF-8"));
cp_utf8_cache.put(j + 1, sval);
i += utf8_length;
break;
case 3://integer
case 4://float
i += 4;
break;
case 5://long
case 6://double
j++;
i += 8;
break;
case 7://class
i += 2;
break;
case 8://string
i += 2;
break;
case 9://fieldref
case 10://methodref
case 11://interfacemethodref
i += 4;
break;
case 12:
i += 4;//name and type
break;
case 15: // methodhandle
i += 3;
break;
case 16: // methodtype
i += 2;
break;
case 18: // invokedynamic
i += 4;
break;
case 19: // moduleId
case 20: // moduleQuery
i += 4;
break;
default:
logger.log(Level.SEVERE, "SHOULD NOT OCCUR: unknown cp_type: {0}", cp_type);
break;
}
}
i += 2;//skip access flags
i += 2;//skip this class
i += 2;//skip super class
int i_count = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;//skip interfaces count
i += 2 * i_count;//skip interfaces table
// Process fields
int fld_count = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;
byte[] clone = new byte[classfileBuffer.length];
int clone_ptr = i;
// Copy all processed data to the clone
System.arraycopy(classfileBuffer, 0, clone, 0, clone_ptr);
for (int j = 0; j < fld_count; j++) {
int f_start = i;
i += 2 * 3;
int attr_count = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;
int[][] attr_ptrs = new int[attr_count][2];
int clone_attr_count = 0;
for (int k = 0; k < attr_count; k++) {
int name_index = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;//skip attr name
long fld_attr_length = ((classfileBuffer[i] & 0xFF) << 24) | ((classfileBuffer[i + 1] & 0xFF) << 16)
| ((classfileBuffer[i + 2] & 0xFF) << 8) | (classfileBuffer[i + 3] & 0xFF);
i += 4;//skip attr length
i += fld_attr_length;
if (!cp_utf8_cache.get(name_index).contains("Deprecated") /*&&
!cp_utf8_cache.get(name_index).contains("ConstantValue")*/) {// skip deprecated attribute
attr_ptrs[clone_attr_count][1] = 2 + 4 + (int) fld_attr_length;
attr_ptrs[clone_attr_count][0] = i - attr_ptrs[clone_attr_count][1];
clone_attr_count++;
}
}
System.arraycopy(classfileBuffer, f_start, clone, clone_ptr, 6);
clone_ptr += 6;
clone[clone_ptr++] = (byte) (clone_attr_count >> 8);
clone[clone_ptr++] = (byte) clone_attr_count;
// copy all required field attributes
for (int l = 0; l < clone_attr_count; l++) {
System.arraycopy(classfileBuffer, attr_ptrs[l][0], clone, clone_ptr, attr_ptrs[l][1]);
clone_ptr += attr_ptrs[l][1];
}
}
// Process methods. Methods are sorted by their name + description befor
// being written to the clone
int mth_count = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
clone[clone_ptr] = classfileBuffer[i];
clone_ptr++;
i++;
clone[clone_ptr] = classfileBuffer[i];
clone_ptr++;
i++;
TreeMap<String, byte[]> methods = new TreeMap();
for (int j = 0; j < mth_count; j++) {
int m_start = i;
i += 2;
int name_index = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;
int descriptor_index = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;
int attr_count = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;//skip count;
int[][] attr_ptrs = new int[attr_count][2];
int clone_attr_count = 0;
int whole_attr_length = 0;
for (int k = 0; k < attr_count; k++) {
int attr_name_index = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;//skip attr name
long mth_attr_length = ((classfileBuffer[i] & 0xFF) << 24) | ((classfileBuffer[i + 1] & 0xFF) << 16)
| ((classfileBuffer[i + 2] & 0xFF) << 8) | (classfileBuffer[i + 3] & 0xFF);
i += 4;//skip attr length
i += mth_attr_length;
if (!cp_utf8_cache.get(attr_name_index).contains("Deprecated")) {// skip deprecated attribute
attr_ptrs[clone_attr_count][1] = 2 + 4 + (int) mth_attr_length;
whole_attr_length += attr_ptrs[clone_attr_count][1];
attr_ptrs[clone_attr_count][0] = i - attr_ptrs[clone_attr_count][1];
clone_attr_count++;
}
}
byte[] data = new byte[2 * 4 + whole_attr_length];
System.arraycopy(classfileBuffer, m_start, data, 0, 6);
data[6] = (byte) (clone_attr_count >> 8);
data[7] = (byte) clone_attr_count;
int data_ptr = 0;
for (int l = 0; l < clone_attr_count; l++) {
System.arraycopy(classfileBuffer, attr_ptrs[l][0], data, data_ptr + 8, attr_ptrs[l][1]);
data_ptr += attr_ptrs[l][1];
}
methods.put(cp_utf8_cache.get(name_index) + cp_utf8_cache.get(descriptor_index), data);
}
// sorting methods
for (byte data[] : methods.values()) {
System.arraycopy(data, 0, clone, clone_ptr, data.length);
clone_ptr += data.length;
}
// for (String key : methods.keySet()) {
// int length = methods.get(key).length;
// System.arraycopy(methods.get(key), 0, clone, clone_ptr, length);
// clone_ptr += length;
// }
// Process class attributes. They are sorted by their names. Some are skipped.
TreeMap<String, byte[]> attributes = new TreeMap();
int attr_count = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;
int clone_attr_count = 0;
for (int k = 0; k < attr_count; k++) {
int name_index = ((classfileBuffer[i] & 0xFF) << 8) | (classfileBuffer[i + 1] & 0xFF);
i += 2;//skip attr name
long class_attr_length = ((classfileBuffer[i] & 0xFF) << 24) | ((classfileBuffer[i + 1] & 0xFF) << 16)
| ((classfileBuffer[i + 2] & 0xFF) << 8) | (classfileBuffer[i + 3] & 0xFF);
i += 4;//skip attr length
i += class_attr_length;
if (!cp_utf8_cache.get(name_index).contains("Deprecated")
&& !cp_utf8_cache.get(name_index).contains("EnclosingMethod")) {
clone_attr_count++;
byte[] data = new byte[2 + 4 + (int) class_attr_length];
System.arraycopy(classfileBuffer, i - data.length, data, 0, data.length);
attributes.put(cp_utf8_cache.get(name_index), data);
}
}
clone[clone_ptr++] = (byte) (clone_attr_count >> 8);
clone[clone_ptr++] = (byte) clone_attr_count;
// Sorting attributes
for (byte data[] : attributes.values()) {
System.arraycopy(data, 0, clone, clone_ptr, data.length);
clone_ptr += data.length;
}
// for (String key : attributes.keySet()) {
// int length = attributes.get(key).length;
// System.arraycopy(attributes.get(key), 0, clone, clone_ptr, length);
// clone_ptr += length;
// }
Adler32 adler = new Adler32();
adler.update(clone, 0, clone_ptr);
long checksum = adler.getValue();
return checksum;
}
public void updateModuleInfo(HashMap<String, String> moduleInfo){
if (root != null){
for (DataPackage pack : root.getPackages()){
String moduleName = moduleInfo.get(pack.getName());
if (moduleName != null) {
pack.setModuleName(moduleName);
}
}
}
}
private void findAlreadyInstrumentedAndSetID() {
try {
if (outputFile == null) {
return;
}
File file = new File(outputFile);
if (!file.exists()) {
return;
}
DataRoot r;
if (params.isDynamicCollect()) {
r = Reader.readXMLHeader(outputFile);
} else {
r = Reader.readXML(outputFile, true, null);
for (DataPackage pack : r.getPackages()) {
for (DataClass clazz : pack.getClasses()) {
instrumented.put(clazz.getFullname(), clazz.getChecksum());
}
}
}
Collect.setSlot(r.getCount());
r.destroy();
} catch (FileFormatException ffe) {
System.err.println("Wrong format of the output file: "+outputFile+". " +
"Delete output file to receive coverage data");
} catch (Exception e) {
throw new Error(e);
}
}
public static void fillIntrMethodsIDs(DataRoot root){
try {
for (DataPackage pack : root.getPackages()) {
for (DataClass clazz : pack.getClasses()) {
for (DataMethod meth : clazz.getMethods()) {
if (meth.access(meth.getModifiers()).matches(".*abstract.*")
|| meth.access(meth.getModifiers()).matches(".*native.*")) {
int id = 0;
if (meth instanceof DataMethodInvoked) {
id = ((DataMethodInvoked) meth).getId();
} else if (meth instanceof DataMethodEntryOnly) {
id = ((DataMethodEntryOnly) meth).getId();
} else {
DataMethodWithBlocks mb = (DataMethodWithBlocks) meth;
for (BasicBlock bb : mb.getBasicBlocks()) {
for (DataBlock db : bb.blocks()) {
id = db.getId();
break;
}
break;
}
}
String className = pack.getName().equals("") ? clazz.getName()
: pack.getName().replace('.', '/') + "/" + clazz.getName();
StaticInvokeMethodAdapter.addID(
className, meth.getName(), meth.getVmSignature(), id);
if (meth.getAnnotations()!= null ) {
for (String annotation : meth.getAnnotations()) {
if (annotation != null && annotation.contains("PolymorphicSignature")) {
StaticInvokeMethodAdapter.addID(
className, meth.getName(), "", id);
break;
}
}
}
}
}
for (DataField fld : clazz.getFields()) {
int id = fld.getId();
String className = pack.getName().equals("") ? clazz.getName()
: pack.getName().replace('.', '/') + "/" + clazz.getName();
StaticInvokeMethodAdapter.addID(
className, fld.getName(), fld.getVmSig(), id);
}
}
}
} catch (Throwable t) {
throw new Error(t);
}
}
public void saveData(InstrumentationOptions.MERGE merge) {
FileSaver fileSaver = FileSaver.getFileSaver(root, outputFile, outputFile, merge, true, false);
fileSaver.saveResults();
}
public void saveData(String outputFile, InstrumentationOptions.MERGE merge) {
FileSaver fileSaver = FileSaver.getFileSaver(root, outputFile, outputFile, merge, true, false);
fileSaver.saveResults();
}
/**
* <p> Saves collected DataRoot (template) </p>
*
* @param outputTemplateFile File to save the template to
* @param initialTemplatePath Template to use for saving the new template
* (would be merged). Can be null if no merging with old template needed
* @param merge Merging type used in case <code>outputTemplateFile</code>
* file already exists
*/
public void saveData(String outputTemplateFile, String initialTemplatePath, InstrumentationOptions.MERGE merge) {
FileSaver fileSaver = FileSaver.getFileSaver(root, outputTemplateFile, initialTemplatePath, merge, true, false);
fileSaver.saveResults();
}
public final static OptionDescr DSC_FLUSH_CLASSES =
new OptionDescr("flush", null, "flush instrumented classes",
OptionDescr.VAL_SINGLE, null, "Specify path to directory, where to store instrumented classes.\n"
+ "Directory should exist. Classes will be saved in respect to their package hierarchy.\n"
+ "Default value is \"none\". Pushing it means you don't want to flush classes.", "none");
private boolean isPreVMLoadClass(String fullname) {
// classes (actually only certain packages needed) which are loaded before
// VM is loaded - add classname (eg through new Exception().getStackTrace()[0])
// saving to Collect.hit
return fullname.startsWith("java/lang")
|| fullname.startsWith("sun")
|| fullname.startsWith("java/util");
}
}
| 30,768 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Instrumenter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/Instrumenter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.DataBlock;
import com.sun.tdk.jcov.instrument.SimpleBasicBlock;
import org.objectweb.asm.tree.*;
import org.objectweb.asm.MethodVisitor;
import static org.objectweb.asm.Opcodes.*;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
class Instrumenter {
private static InsnList instrumentation(int id, boolean detectInternal) {
return instrumentation(id, 0, 0, detectInternal);
}
private static InsnList instrumentation(int id, int hash, int fullHash, boolean detectInternal) {
InsnList il = new InsnList();
if (hash != 0 || fullHash != 0) { // caller filter ON (hash & fullHash == 0 otherwise)
il.add(new LdcInsnNode(id));
il.add(new LdcInsnNode(hash));
il.add(new LdcInsnNode(fullHash));
il.add(new MethodInsnNode(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/CollectDetect", "hit", "(III)V", false));
} else if (detectInternal) { // agent (hardcoded by default) or loaded, false otherwise
il.add(new LdcInsnNode(id));
il.add(new MethodInsnNode(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/CollectDetect", "hit", "(I)V", false));
} else { // static
il.add(new LdcInsnNode(id));
il.add(new MethodInsnNode(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/Collect", "hit", "(I)V", false));
}
return il;
}
public static InsnList instrumentation(DataBlock block, boolean detectInternal) {
return instrumentation(block.getId(), detectInternal);
}
public static InsnList instrumentation(SimpleBasicBlock block, boolean detectInternal) {
return instrumentation(block.getId(), detectInternal);
}
static void visitInstrumentation(final MethodVisitor mv, int id, int hash, int fullHash, boolean detectInternal) {
instrumentation(id, hash, fullHash, detectInternal).accept(mv);
}
/*
static InsnList insertSavePoint() {
InsnList il = new InsnList();
il.add(new MethodInsnNode(INVOKESTATIC, "com/sun/tdk/jcov/runtime/Collect","saveResults", "(V)V"));
return il;
}
*/
}
| 3,456 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
OffsetRecordingMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/OffsetRecordingMethodAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.DataMethodWithBlocks;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Handle;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Label;
/**
* OffsetRecordingMethodAdapter
*
* @author Robert Field
*/
class OffsetRecordingMethodAdapter extends MethodVisitor {
private int currentOffset;
private int currentInstructionIndex;
protected int[] bcis;
protected final DataMethodWithBlocks method;
public OffsetRecordingMethodAdapter(final MethodVisitor mv,
final DataMethodWithBlocks method) {
super(ASMUtils.ASM_API_VERSION, mv);
this.currentInstructionIndex = 0;
this.bcis = new int[60];
this.method = method;
}
DataMethodWithBlocks method() {
return method;
}
private void recordInstructionOffset() {
if (currentInstructionIndex >= bcis.length) {
bcis = Utils.copyOf(bcis, bcis.length * 2);
}
bcis[currentInstructionIndex++] = currentOffset;
}
public void visitLabel(final Label label) {
OffsetLabel ol = (OffsetLabel) label;
currentOffset = ol.originalOffset;
if (ol.realLabel) {
super.visitLabel(label);
}
}
public void visitInsn(final int opcode) {
recordInstructionOffset();
super.visitInsn(opcode);
}
public void visitIntInsn(final int opcode, final int operand) {
recordInstructionOffset();
super.visitIntInsn(opcode, operand);
}
public void visitVarInsn(final int opcode, final int var) {
recordInstructionOffset();
super.visitVarInsn(opcode, var);
}
public void visitTypeInsn(final int opcode, final String desc) {
recordInstructionOffset();
super.visitTypeInsn(opcode, desc);
}
public void visitFieldInsn(
final int opcode,
final String owner,
final String name,
final String desc) {
recordInstructionOffset();
super.visitFieldInsn(opcode, owner, name, desc);
}
public void visitJumpInsn(final int opcode, final Label label) {
recordInstructionOffset();
super.visitJumpInsn(opcode, label);
}
public void visitLdcInsn(final Object cst) {
recordInstructionOffset();
super.visitLdcInsn(cst);
}
public void visitIincInsn(final int var, final int increment) {
recordInstructionOffset();
super.visitIincInsn(var, increment);
}
public void visitTableSwitchInsn(
final int min,
final int max,
final Label dflt,
final Label labels[]) {
recordInstructionOffset();
super.visitTableSwitchInsn(min, max, dflt, labels);
}
public void visitLookupSwitchInsn(
final Label dflt,
final int keys[],
final Label labels[]) {
recordInstructionOffset();
super.visitLookupSwitchInsn(dflt, keys, labels);
}
public void visitMultiANewArrayInsn(final String desc, final int dims) {
recordInstructionOffset();
super.visitMultiANewArrayInsn(desc, dims);
}
@Override
public AnnotationVisitor visitAnnotation(String anno, boolean b) {
method().addAnnotation(anno);
return super.visitAnnotation(anno, b);
}
@Override
public void visitEnd() {
recordInstructionOffset(); // record end
method().setBytecodeLength(currentOffset); // and set as method length
super.visitEnd();
}
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
recordInstructionOffset();
super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
recordInstructionOffset();
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
}
| 5,308 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
BlockCodeMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/BlockCodeMethodAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import java.util.*;
import static org.objectweb.asm.Opcodes.*;
import com.sun.tdk.jcov.instrument.CharacterRangeTable;
import com.sun.tdk.jcov.instrument.DataBlock;
import com.sun.tdk.jcov.instrument.DataBlockFallThrough;
import com.sun.tdk.jcov.instrument.DataBlockTargetDefault;
import com.sun.tdk.jcov.instrument.DataBranchCond;
import com.sun.tdk.jcov.instrument.DataBranchGoto;
import com.sun.tdk.jcov.instrument.DataBranchSwitch;
import com.sun.tdk.jcov.instrument.DataExit;
import com.sun.tdk.jcov.instrument.DataExitSimple;
import com.sun.tdk.jcov.instrument.DataMethodWithBlocks;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import com.sun.tdk.jcov.instrument.SimpleBasicBlock;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.tree.*;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
class BlockCodeMethodAdapter extends OffsetRecordingMethodAdapter {
private final MethodVisitor nextVisitor;
private final List<DataExit> exits;
private final Map<AbstractInsnNode, SimpleBasicBlock> insnToBB;
private final InstrumentationParams params;
public BlockCodeMethodAdapter(final MethodVisitor mv,
final DataMethodWithBlocks method,
final InstrumentationParams params) {
super(new MethodNode(method.getAccess(), method.getName(), method.getVmSignature(), method.getSignature(), method.getExceptions()),
method);
this.nextVisitor = mv;
this.insnToBB = new IdentityHashMap<AbstractInsnNode, SimpleBasicBlock>();
this.exits = new ArrayList<DataExit>();
this.params = params;
}
private SimpleBasicBlock getBB(AbstractInsnNode insn, int startBCI) {
SimpleBasicBlock bb = insnToBB.get(insn);
if (bb == null) {
bb = new SimpleBasicBlock(method.rootId(), startBCI);
insnToBB.put(insn, bb);
} else if (startBCI >= 0) {
bb.setStartBCI(startBCI);
}
return bb;
}
private SimpleBasicBlock getBB(AbstractInsnNode insn) {
return getBB(insn, -1);
}
private AbstractInsnNode peek(ListIterator iit) {
// Do a next() to get the next instruction..
// Then immediately do a previous to restore our position.
if (iit.hasNext()) {
AbstractInsnNode insn = (AbstractInsnNode) iit.next();
iit.previous();
return insn;
}
return null;
}
private SimpleBasicBlock[] completeComputationOfCodeLabelNodes() {
MethodNode methodNode = (MethodNode) mv;
InsnList instructions = methodNode.instructions;
int[] allToReal = new int[instructions.size()];
int allIdx = 0;
int insnIdx = 0;
ListIterator iit = instructions.iterator();
// Create the method entry block and basic block
AbstractInsnNode insnFirst = peek(iit);
SimpleBasicBlock bbFirst = getBB(insnFirst, 0);
// DataBlock blockFirst = new DataBlockMethEnter();
// bbFirst.add(blockFirst);
while (iit.hasNext()) {
AbstractInsnNode insn = (AbstractInsnNode) iit.next();
allToReal[allIdx++] = insnIdx;
int bci = bcis[insnIdx];
int opcode = insn.getOpcode();
if (opcode < 0) {
// a pseudo-instruction
if (insn.getType() == AbstractInsnNode.LINE) {
LineNumberNode lineNode = (LineNumberNode) insn;
method().addLineEntry(bci, lineNode.line);
}
} else {
// a real instruction
++insnIdx; // advance the real instruction index
//System.out.println( "#" + (insnIdx - 1) +
// " bci: " + bci + " " +
// instr.toString().replace("org.objectweb.asm.tree.", "").replace("@", " @ ") +
// " [" + (opcode>=0? Constants.opcNames[opcode] : " pseudo") +"]");
switch (opcode) {
case IFEQ:
case IFNE:
case IFLT:
case IFGE:
case IFGT:
case IFLE:
case IF_ICMPEQ:
case IF_ICMPNE:
case IF_ICMPLT:
case IF_ICMPGE:
case IF_ICMPGT:
case IF_ICMPLE:
case IF_ACMPEQ:
case IF_ACMPNE:
case IFNULL:
case IFNONNULL:
case JSR: {
JumpInsnNode jumpInsn = (JumpInsnNode) insn;
LabelNode insnTrue = jumpInsn.label;
int bciFalse = bcis[insnIdx]; // fall-through
DataBranchCond branch = new DataBranchCond(method.rootId(), bci, bciFalse - 1);
/* DataBlockTarget blockTrue = new DataBlockTargetCond(true);
DataBlockTarget blockFalse = new DataBlockTargetCond(false);
branch.addTarget(blockTrue);
branch.addTarget(blockFalse);
*/
AbstractInsnNode insnFalse = peek(iit);
assert (insnFalse != null); // must be fall-through code
SimpleBasicBlock bbTrue = getBB(insnTrue);
SimpleBasicBlock bbFalse = getBB(insnFalse, bciFalse);
exits.add(branch);
// assign a new label for branch counting
// LabelNode nlab = new LabelNode();
// jumpInsn.label = nlab; // branch to new label
// bbTrue.add(blockTrue, nlab);
//bbFalse.add(blockFalse);
break;
}
case TABLESWITCH: {
TableSwitchInsnNode switchInsn = (TableSwitchInsnNode) insn;
// Create a block and basic-block the "default:" case
LabelNode insnDflt = switchInsn.dflt;
SimpleBasicBlock bbDefault = getBB(insnDflt);
DataBlockTargetDefault blockDefault = new DataBlockTargetDefault(bbDefault.rootId());
// assign a new default label for branch counting
//LabelNode nlab = new LabelNode();
//switchInsn.dflt = nlab; // branch to new label
//bbDefault.add(blockDefault, nlab);
// Create the branch information
int bciEnd = bcis[insnIdx] - 1; // end of the switch
DataBranchSwitch branch = new DataBranchSwitch(method.rootId(), bci, bciEnd, blockDefault);
// branch.addTarget(blockDefault);
exits.add(branch);
// Process the other cases
ListIterator lit = switchInsn.labels.listIterator();
int key = switchInsn.min;
while (lit.hasNext()) {
// Create a block and basic-block the case
LabelNode labCase = (LabelNode) lit.next();
SimpleBasicBlock bbCase = getBB(labCase);
//DataBlockTargetCase blockCase = new DataBlockTargetCase(key++);
//branch.addTarget(blockCase);
// assign a new label to the case for branch counting
//nlab = new LabelNode();
// lit.set(nlab);
// bbCase.add(blockCase, nlab);
}
break;
}
case LOOKUPSWITCH: {
LookupSwitchInsnNode switchInsn = (LookupSwitchInsnNode) insn;
// Create a block and basic-block the "default:" case
LabelNode insnDflt = switchInsn.dflt;
SimpleBasicBlock bbDefault = getBB(insnDflt);
DataBlockTargetDefault blockDefault = new DataBlockTargetDefault(bbDefault.rootId());
// assign a new default label for branch counting
// LabelNode nlab = new LabelNode();
// switchInsn.dflt = nlab; // branch to new label
// bbDefault.add(blockDefault, nlab);
// Create the branch information
int bciEnd = bcis[insnIdx] - 1; // end of the switch
DataBranchSwitch branch = new DataBranchSwitch(method.rootId(), bci, bciEnd, blockDefault);
// branch.addTarget(blockDefault);
exits.add(branch);
// Process the other cases
ListIterator kit = switchInsn.keys.listIterator();
ListIterator lit = switchInsn.labels.listIterator();
while (lit.hasNext()) {
// Create a block and basic-block the case
LabelNode labCase = (LabelNode) lit.next();
SimpleBasicBlock bbCase = getBB(labCase);
Integer key = (Integer) kit.next();
// DataBlockTargetCase blockCase = new DataBlockTargetCase(key.intValue());
// branch.addTarget(blockCase);
// assign a new label to the case for branch counting
//nlab = new LabelNode();
//lit.set(nlab);
//bbCase.add(blockCase, nlab);
}
break;
}
case GOTO: {
JumpInsnNode jumpInsn = (JumpInsnNode) insn;
// Create origin info, a branch
int bciEnd = bcis[insnIdx] - 1;
DataBranchGoto branch = new DataBranchGoto(method.rootId(), bci, bciEnd);
exits.add(branch);
// Create destination info, a block target
LabelNode insnTarget = jumpInsn.label;
SimpleBasicBlock bbTarget = getBB(insnTarget);
//DataBlockTarget blockTarget = new DataBlockTargetGoto();
//branch.addTarget(blockTarget);
// assign a new label for branch counting
//LabelNode nlab = new LabelNode();
//jumpInsn.label = nlab; // branch to new label
//bbTarget.add(blockTarget, nlab);
break;
}
case ATHROW:
case RET:
case IRETURN:
case LRETURN:
case FRETURN:
case DRETURN:
case ARETURN:
case RETURN: {
int bciNext = bcis[insnIdx];
DataExit exit = new DataExitSimple(method.rootId(), bci, bciNext - 1, insn.getOpcode());
exits.add(exit);
AbstractInsnNode insnNext = peek(iit);
if (insnNext != null) {
// If there is code after this, it has to be the start of a
// new basic block
getBB(insnNext, bciNext);
}
break;
}
default:
break;
}
// try add src block
}
}
// Now go through the try-catch blocks
LabelNode previousHandler = null;
for (Iterator tbit = methodNode.tryCatchBlocks.iterator(); tbit.hasNext();) {
TryCatchBlockNode tcbn = (TryCatchBlockNode) tbit.next();
LabelNode insnHandler = tcbn.handler;
if (insnHandler != previousHandler) {
previousHandler = insnHandler;
// Create destination info, a block target
SimpleBasicBlock bbCatch = getBB(insnHandler);
}
}
if (method().getCharacterRangeTable() != null) {
boolean newBlock = true;
int skip = 0;
iit = instructions.iterator();
while (iit.hasNext()) {
AbstractInsnNode insn = (AbstractInsnNode) iit.next();
int index = instructions.indexOf(insn);
int bci = bcis[allToReal[index]];
if (bci == skip) {
continue;
}
if (insnToBB.get(insn) != null) {
skip = bcis[allToReal[ instructions.indexOf(insn)]];
}
if (insn.getOpcode() < 0) {
continue;
}
for (CharacterRangeTable.CRTEntry entry : method().getCharacterRangeTable().getEntries()) {
if (entry.startBCI() == bci) {
if ((entry.flags & CharacterRangeTable.CRTEntry.CRT_STATEMENT) != 0 /*& newBlock*/) {
newBlock = false;
if (insnToBB.get(insn) == null) {
//System.out.println("Should add block at: " + bci + " in " + method().name +
// " for " + Constants.opcNames[insn.getOpcode()]);
getBB(insn);
break;
}
}
} else {
if (entry.endBCI() == index && (entry.flags & CharacterRangeTable.CRTEntry.CRT_FLOW_TARGET) != 0) {
newBlock = true;
}
}
}
}
}
// Compute the startBCI for any basic blocks that don't have it'
SimpleBasicBlock[] basicBlocks = new SimpleBasicBlock[insnToBB.size()];
int i = 0;
for (Map.Entry<AbstractInsnNode, SimpleBasicBlock> entry : insnToBB.entrySet()) {
SimpleBasicBlock bb = entry.getValue();
if (bb.startBCI() < 0) {
AbstractInsnNode insn = entry.getKey();
int index = instructions.indexOf(insn);
int bci = bcis[allToReal[index]];
bb.setStartBCI(bci);
}
basicBlocks[i++] = bb;
}
Arrays.sort(basicBlocks);
return basicBlocks;
}
/**
* Compute end BCIs for basic blocks, then set this info into detail blocks.
* Assumes the basic blocks are sorted
*/
private void computeEndBCIsAndFoldInExits(SimpleBasicBlock[] basicBlocks) {
int ei = 0; // exit index
SimpleBasicBlock prev = basicBlocks[0];
for (int bi = 1; bi <= basicBlocks.length; ++bi) {
SimpleBasicBlock curr = null;
int start;
if (bi == basicBlocks.length) {
start = method().getBytecodeLength();
} else {
curr = basicBlocks[bi];
start = curr.startBCI();
}
int prevStart = prev.startBCI();
// Set the previous block to end just before the current starts
int prevEnd = start - 1;
prev.setEndBCI(prevEnd);
// Now that we know the endBCI, we can determine if
// any exits reside in this range
DataExit exit = null;
int exitStart;
if (ei < exits.size()) {
exit = exits.get(ei);
exitStart = exit.startBCI();
} else {
exitStart = -1; // always go to the fall-into code
}
if (exitStart >= prevStart && exitStart <= prevEnd) {
// The exit is in the prev block attach it
prev.setExit(exit);
// System.out.println("found " + ei + " BB: " + prev + " exit: " + exit);
++ei; // set-up to handle the next exit
} else {
// There is no exit from the prev block, so we fall
// into the curr block (if any)
if (curr != null) {
DataBlock fall = new DataBlockFallThrough(curr.rootId());
curr.add(fall);
}
}
prev = curr;
}
// System.out.println("ei: " + ei + " / " + exits.size());
assert (ei == exits.size());
}
private void insertInstrumentation() {
MethodNode methodNode = (MethodNode) mv;
InsnList instructions = methodNode.instructions;
for (Map.Entry<AbstractInsnNode, SimpleBasicBlock> entry : insnToBB.entrySet()) {
// Basic block 'bb' starts at instruction 'insn'
AbstractInsnNode insn = entry.getKey();
SimpleBasicBlock bb = entry.getValue();
// System.out.println("insn = " + insn);
instructions.insert(insn, Instrumenter.instrumentation(bb, params.isDetectInternal()));
}
}
@Override
public void visitAttribute(Attribute attr) {
super.visitAttribute(attr);
if (attr instanceof CharacterRangeTableAttribute) {
method().setCharacterRangeTable(((CharacterRangeTableAttribute) attr).getCrt());
}
}
// the instruction list has been built, insert the instrumentation
@Override
public void visitEnd() {
super.visitEnd();
SimpleBasicBlock[] basicBlocks = completeComputationOfCodeLabelNodes();
computeEndBCIsAndFoldInExits(basicBlocks);
//debugDump();
insertInstrumentation();
method().setBasicBlocks(basicBlocks);
// push the result to the writer
MethodNode methodNode = (MethodNode) mv;
methodNode.accept(nextVisitor);
}
}
| 19,561 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DeferringMethodClassAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/DeferringMethodClassAdapter.java | /*
* Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.instrument.DataMethod;
import com.sun.tdk.jcov.instrument.DataMethodEntryOnly;
import com.sun.tdk.jcov.instrument.DataMethodInvoked;
import com.sun.tdk.jcov.instrument.DataMethodWithBlocks;
import com.sun.tdk.jcov.instrument.InstrumentationOptions;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import static org.objectweb.asm.Opcodes.*;
import org.objectweb.asm.tree.MethodNode;
import java.util.logging.Logger;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
class DeferringMethodClassAdapter extends ClassVisitor {
private final DataClass dataClass;
private final InstrumentationParams params;
private static final Logger logger = Logger.getLogger("com.sun.tdk.jcov");
public DeferringMethodClassAdapter(final ClassVisitor cv, DataClass dataClass, InstrumentationParams params) {
super(ASMUtils.ASM_API_VERSION, cv);
this.dataClass = dataClass;
this.params = params;
}
@Override
public void visit(
final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces) {
dataClass.setInfo(new ASMModifiers(access), signature, superName, interfaces);
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
// the (access & ACC_STATIC) == 0 || value ==null means
// that class is not substitued by value during comilation
FieldVisitor fv = super.visitField(access, name, desc, signature, value);
if (params.isInstrumentFields() && ((access & ACC_STATIC) == 0 || value == null)) {
DataField fld = new DataField(dataClass, access, name, desc, signature, value);
fv = new FieldAnnotationVisitor(fv, fld);
// this is needed, because DataField contains adding to DataClass
}
return fv;
}
@Override
public void visitSource(String source, String debug) {
dataClass.setSource(source);
super.visitSource(source, debug);
}
public MethodVisitor visitMethodCoverage(
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions) {
if (!InstrumentationOptions.isSkipped(dataClass.getFullname(), name, access)
&& params.isDynamicCollect()
&& params.isInstrumentNative()
&& (access & ACC_NATIVE) != 0
&& !"java/lang/invoke/VarHandle".equals(dataClass.getFullname())) {
// Visit the native method, but change the access flags and rename it with a prefix
int accessNative = access;
if ((accessNative & ACC_STATIC) == 0) {
// not static, then it needs to be final
accessNative |= ACC_FINAL;
}
accessNative &= ~(ACC_PUBLIC | ACC_PROTECTED);
accessNative |= ACC_PRIVATE;
MethodVisitor mvNative = cv.visitMethod(
accessNative,
InstrumentationOptions.nativePrefix + name,
desc,
signature,
exceptions);
if (mvNative == null) {
throw new InternalError("Should not happen!");
}
// Write the native method, then visit and write the wrapper method
MethodNode methodWrapper = new MethodNode(access & ~ACC_NATIVE, name, desc, signature, exceptions);
DataMethodEntryOnly meth = new DataMethodEntryOnly(dataClass, access, name, desc, signature, exceptions);
return new NativeWrappingMethodAdapter(mvNative, methodWrapper, cv, meth, params);
}
MethodVisitor mv = cv.visitMethod(access,
name,
desc,
signature,
exceptions);
//This code is executed both in dynamic and static mode
if (InstrumentationOptions.isSkipped(dataClass.getFullname(), name, access) ||
mv == null ||
(access & ACC_ABSTRACT) != 0 ||
(access & ACC_NATIVE) != 0) {
// build method with no content, and we are done
if ((access & ACC_ABSTRACT) != 0 && params.isInstrumentAbstract()
|| ((access & ACC_NATIVE) != 0 && params.isInstrumentNative())
|| InstrumentationOptions.isSkipped(dataClass.getFullname(), name, access)) {
DataMethod meth = new DataMethodInvoked(dataClass, access, name, desc, signature, exceptions);
return new MethodAnnotationAdapter(mv, meth);
}
return mv;
}
// method could not be instrumented
// java.lang.VerifyError: (class: sun/awt/X11/XWindowPeer, method: handleButtonPressRelease signature: (IJ)V) Mismatched stack types
// temporary use only method coverage
if (dataClass.getFullname().equals("sun/awt/X11/XWindowPeer") && name.equals("handleButtonPressRelease")) {
DataMethodEntryOnly meth = new DataMethodEntryOnly(dataClass, access, name, desc, signature, exceptions);
return new EntryCodeMethodAdapter(mv, meth, params);
}
switch (params.getMode()) {
case METHOD: {
DataMethodEntryOnly meth = new DataMethodEntryOnly(dataClass, access, name, desc, signature, exceptions);
return new EntryCodeMethodAdapter(mv, meth, params);
}
case BLOCK: {
DataMethodWithBlocks meth = new DataMethodWithBlocks(dataClass, access, name, desc, signature, exceptions);
return new BlockCodeMethodAdapter(mv, meth, params);
}
case BRANCH: {
DataMethodWithBlocks meth = new DataMethodWithBlocks(dataClass, access, name, desc, signature, exceptions);
return new BranchCodeMethodAdapter(mv, meth, params);
}
default:
break;
}
return null;
}
/**
* Visit a method declaration
*/
@Override
public MethodVisitor visitMethod(int access, String methodName, String desc, String signature, String[] exceptions) {
if (!params.isInstrumentSynthetic() && (access & ACC_SYNTHETIC) != 0) {
return super.visitMethod(access, methodName, desc, signature, exceptions);
}
MethodVisitor mv = visitMethodCoverage(access, methodName, desc, signature, exceptions);
if ("<clinit>".equals(methodName) &&
!params.isDynamicCollect() &&
(dataClass.getPackageName().startsWith("java/lang/"))) {
mv = new MethodVisitor(ASMUtils.ASM_API_VERSION, mv) {
public void visitCode() {
mv.visitMethodInsn(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/Collect", "init", "()V",
false);
super.visitCode();
}
};
}
if (params.isCallerFilterOn()
&& params.isCallerFilterAccept(dataClass.getFullname())
&& !params.isDynamicCollect()) {
if (methodName.equals("<clinit>")) {
int id = (methodName + desc).hashCode();
mv.visitLdcInsn(id);
mv.visitMethodInsn(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/CollectDetect", "setExpected", "(I)V",
false);
}
}
if (params.isInnerInvacationsOff() &&
Utils.isAdvanceStaticInstrAllowed(dataClass.getFullname(), methodName)) {
if (methodName.equals("<clinit>")) {
mv.visitMethodInsn(INVOKESTATIC, "com/sun/tdk/jcov/runtime/CollectDetect",
"enterClinit",
"()V",
false);
}
}
if (params.isDataSaveFilterAccept(dataClass.getFullname(), methodName, true)) {
mv = new SavePointsMethodAdapter(mv, true);
}
if (params.isDataSaveFilterAccept(dataClass.getFullname(), methodName, false)) {
mv = new SavePointsMethodAdapter(mv, false);
}
mv = new MethodVisitor(ASMUtils.ASM_API_VERSION, mv) {
@Override
public void visitLocalVariable(String arg0, String arg1, String arg2, Label arg3, Label arg4, int arg5) {
//super.visitLocalVariable(arg0, arg1, arg2, arg3, arg4, arg5);
}
};
if (params.isDynamicCollect()) {
mv = new InvokeMethodAdapter(mv, dataClass.getFullname(), params);
} else {
mv = new StaticInvokeMethodAdapter(mv, dataClass.getFullname(), methodName, access, params);
}
ASMInstrumentationPlugin plugin = (ASMInstrumentationPlugin) params.getInstrumentationPlugin();
if (plugin != null)
mv = plugin.methodVisitor(access, dataClass.getFullname(), methodName, desc, mv);
return mv;
}
@Override
public AnnotationVisitor visitAnnotation(String anno, boolean b) {
dataClass.addAnnotation(anno);
return super.visitAnnotation(anno, b);
}
@Override
public void visitInnerClass(String fullClassName, String parentClass, String className, int i) {
if (!params.isInstrumentAnonymous()) {
return; // ignore
}
// fullClassName can't be null - it's generated if the class is anonym
// className is individual name as written in the source - anonym classes have null there
try {
if (dataClass.getFullname().equals(fullClassName)) {
dataClass.setInner(true);
dataClass.setAnonym(className == null);
}
} catch (Exception e) {
}
super.visitInnerClass(fullClassName, parentClass, className, i);
}
}
| 11,724 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
EntryCodeMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/EntryCodeMethodAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.DataMethodEntryOnly;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
class EntryCodeMethodAdapter extends MethodVisitor {
private final DataMethodEntryOnly method;
boolean isLineNumberVisited = false;
private final InstrumentationParams params;
EntryCodeMethodAdapter(final MethodVisitor mv,
final DataMethodEntryOnly method,
final InstrumentationParams params) {
super(ASMUtils.ASM_API_VERSION, mv);
this.method = method;
this.params = params;
}
@Override
public void visitCode() {
super.visitCode();
int id = 0;
int fullId = 0;
if (params.isCallerFilterOn()) {
if (params.isDynamicCollect() || Utils.isAdvanceStaticInstrAllowed(method.getParent().getFullname(), method.getName())) {
id = (method.getName() + method.getVmSignature()).hashCode();
fullId = (method.getParent().getFullname() + method.getName() + method.getVmSignature()).hashCode();
}
}
if (params.isInnerInvacationsOff() && Utils.isAdvanceStaticInstrAllowed(method.getParent().getFullname(), method.getName())) {
id = -1;
fullId = -1;
if (method.getName().equals("<clinit>")) {
id = 1; //do not count clinit methods like outinvocations
}
}
Instrumenter.visitInstrumentation(mv, method.getId(), id, fullId, params.isDetectInternal());
}
@Override
public void visitMaxs(int maxStack, int maxLocals) {
super.visitMaxs(maxStack < 3 ? 3 : maxStack, maxLocals);
}
@Override
public void visitLineNumber(int line, Label start) {
if (!isLineNumberVisited) {
method.addLineEntry(0, line);
isLineNumberVisited = true;
}
super.visitLineNumber(line, start);
}
@Override
public AnnotationVisitor visitAnnotation(String anno, boolean b) {
method.addAnnotation(anno);
return super.visitAnnotation(anno, b);
}
}
| 3,593 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
InvokeClassAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/InvokeClassAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
/**
*
* @author Leonid Mesnik
*/
public class InvokeClassAdapter extends ClassVisitor {
String className;
private final InstrumentationParams params;
public InvokeClassAdapter(final ClassVisitor cv, final InstrumentationParams params) {
super(ASMUtils.ASM_API_VERSION, cv);
this.params = params;
}
@Override
public void visit(
final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces) {
this.className = name;
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = cv.visitMethod(access,
name,
desc,
signature,
exceptions);
MethodVisitor instr = new InvokeMethodAdapter(mv, className, params);
return instr;
}
}
| 2,511 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CharacterRangeTableAttribute.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/CharacterRangeTableAttribute.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.CharacterRangeTable;
import com.sun.tdk.jcov.instrument.CharacterRangeTable.CRTEntry;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ByteVector;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
/**
* CharacterRangeTableAttribute
*
*
*
* @author Robert Field
*/
public class CharacterRangeTableAttribute extends Attribute {
private CharacterRangeTable crt;
CharacterRangeTableAttribute(CharacterRangeTable crt) {
super("CharacterRangeTable");
this.crt = crt;
}
public CharacterRangeTable getCrt() {
return crt;
}
@Override
public boolean isUnknown() {
return false;
}
void put(CRTEntry entry, ByteVector bv) {
bv.putShort(entry.startBCI());
bv.putShort(entry.endBCI());
bv.putInt(entry.char_start);
bv.putInt(entry.char_end);
bv.putShort(entry.flags);
}
@Override
protected Attribute read(ClassReader cr, int off, int len,
char[] buf, int codeOff, Label[] labels) {
int length = cr.readShort(off);
CRTEntry[] entries = new CRTEntry[length];
for (int i = 0; i < length; ++i) {
int eoff = off + 2 + (i * 14);
int start_pc = cr.readShort(eoff + 0);
int end_pc = cr.readShort(eoff + 2);
int char_start = cr.readInt(eoff + 4);
int char_end = cr.readInt(eoff + 8);
int flags = cr.readShort(eoff + 12);
entries[i] = new CRTEntry(crt.getRootId(), start_pc, end_pc, char_start, char_end, flags);
}
return new CharacterRangeTableAttribute(new CharacterRangeTable(crt.getRootId(), length, entries));
}
@Override
protected ByteVector write(ClassWriter cw, byte[] code, int len,
int maxStack, int maxLocals) {
ByteVector bv = new ByteVector();
bv.putShort(crt.length);
for (CRTEntry entry : crt.entries) {
put(entry, bv);
}
return bv;
}
}
| 3,338 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
OffsetLabel.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/OffsetLabel.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import org.objectweb.asm.Label;
/**
* OffsetLabel
*
* @author Robert Field
*/
class OffsetLabel extends Label {
int originalOffset;
boolean realLabel;
OffsetLabel(int originalOffset) {
this.originalOffset = originalOffset;
}
}
| 1,512 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
OverriddenClassWriter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/OverriddenClassWriter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.JREInstr;
import com.sun.tdk.jcov.runtime.PropertyFinder;
import java.io.IOException;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import static com.sun.tdk.jcov.util.Utils.CUSTOM_CLASS_FILE_EXTENSIONS;
/**
* <p> Extention to ClassWriter where getCommonSuperClass() is overridden. </p>
* <p> It's possible to set custom classfile extension by "clext" property
* (through jcov.clext sys property, JCOV_CLEXT env variable and so on) - eg
* ".clazz". </p> <p> Note that "class" extension has always more priority so
* "Boo.class" will be loaded instead of "Boo.custom". </p>
*
* @author Dmitry Fazunenko
*/
public class OverriddenClassWriter extends ClassWriter {
private final ClassLoader loader;
public OverriddenClassWriter(final ClassReader classReader, final int flags, ClassLoader loader) {
super(classReader, flags);
this.loader = loader;
}
/**
* Overridden implementation which doesn't use Class.forName()
*
* @param type1
* @param type2
* @return
*/
@Override
protected String getCommonSuperClass(final String type1, final String type2) {
return getCommonSuperClassAlt(type1, type2, loader);
}
static String getCommonSuperClassAlt(final String type1, final String type2, ClassLoader loader) {
if (isAssignableFrom(type2, type1, loader)) {
return type2;
}
String type = type1;
while (!isAssignableFrom(type, type2, loader)) {
type = getSuperClass(type, loader);
}
return type;
}
/**
* Map: class name --> super class name
*/
private static final HashMap<String, String> class_superclass =
new HashMap<String, String>();
/**
* Map: class name --> implemented interfaces
*/
private static final HashMap<String, List<String>> class_interfaces =
new HashMap<String, List<String>>();
/**
* The empty list object, to avoid multiple creation of empty lists
*/
private static final List<String> EMPTY_LIST = new ArrayList<String>();
/**
* Cleans collected maps.
*/
public static void clean() {
class_superclass.clear();
class_interfaces.clear();
}
public static void addClassInfo(InputStream in){
try {
ClassReader cr = new OffsetLabelingClassReader(in);
if (class_superclass.get(cr.getClassName()) == null) {
class_superclass.put(cr.getClassName(), cr.getSuperName());
}
if (class_interfaces.get(cr.getClassName()) == null) {
class_interfaces.put(cr.getClassName(), Arrays.asList(cr.getInterfaces()));
}
}
catch (IOException ioe){
System.err.println("Failed to read class. Reason: " + ioe.getMessage());
}
}
/**
* Analog of Class.isAssignableFrom(class2)
*
* @return true if type t1 is assignable from t2.
*/
public static boolean isAssignableFrom(String t1, String t2, final ClassLoader loader) {
if (t1 == null) {
throw new RuntimeException("Can't read superclass bytecode. Please add it to the classpath. ");
}
if (t1.equals(t2)) {
return true;
}
if (t2 == null || t2.equals("java/lang/Object")) {
return false;
}
String superType = getSuperClass(t2, loader); // init interfaces for t2!
List<String> t2Interfaces = class_interfaces.get(t2);
if (t2Interfaces != null && !t2Interfaces.isEmpty()) {
for (String in2 : t2Interfaces) {
if (t1.equals(in2)) {
return true;
}
}
}
return isAssignableFrom(t1, superType, loader);
}
/**
* Returns super class of a given class. For the sake of performance
* returned values are hashed. Method also invokes detectInterfaces() to
* calculate implemented interfaces.
*
* @param clName
* @return
*/
public static String getSuperClass(final String clName, final ClassLoader loader) {
if (clName == null) {
return null;
}
String loaded = class_superclass.get(clName);
if (loaded != null) {
return loaded;
}
try {
ClassInfo ci = getClassInfo(clName, loader);
String superName = ci.getSuperName();
class_superclass.put(clName, superName);
detectInterfaces(clName, ci, loader);
return superName;
} catch (IOException e) {
System.err.println("Failed to read class: " + clName + ". Reason: " + e.getMessage());
}
return null;
}
/**
* Detects interfaces all implemented by the given class. The method updates
* class_interfaces map. For new loaded interfaces class_superclass map is
* also updated to avoid multiple loading.
*
* @param clName
* @param ci
* @throws IOException
*/
static void detectInterfaces(String clName, ClassInfo ci, final ClassLoader loader)
throws IOException {
if (class_interfaces.get(clName) != null) {
return;
}
if (ci == null) {
ci = getClassInfo(clName, loader);
String superName = ci.getSuperName();
class_superclass.put(clName, superName);
}
ArrayList list = new ArrayList();
String[] interfaces = ci.getInterfaces();
if (interfaces != null) {
for (String itf : interfaces) {
list.add(itf);
detectInterfaces(itf, null, loader);
list.addAll(class_interfaces.get(itf));
}
}
if (list.isEmpty()) {
class_interfaces.put(clName, EMPTY_LIST);
} else {
class_interfaces.put(clName, list);
}
}
/**
* Creates ClassReader instance for <b>clName</b> class existing in
* <b>loader</b> ClassLoader
*
* @param clName class to read
* @param loader loader of the clName class
* @return ClassReader
* @throws IOException when class can not be read (not found in loader or
* can't be read by ClassReader)
*/
public static ClassInfo getClassInfo(final String clName, final ClassLoader loader) throws IOException {
ClassInfo classInfo;
if (loader instanceof JREInstr.StaticJREInstrClassLoader) {
InputStream in = getInputStreamForName(clName, loader, false, ".class");
if (in == null) {
in = getInputStreamForName(clName, ClassLoader.getSystemClassLoader(), false, ".class");
if (in == null) {
throw new IOException("Can't read class " + clName + " from classloader " + loader);
}
ClassReader cr = new OffsetLabelingClassReader(in);
classInfo = new ClassInfo(cr.getSuperName(), cr.getInterfaces());
try{
in.close();
}
catch (Throwable ignore){}
return classInfo;
}
ClassReader cr = new OffsetLabelingClassReader(in);
classInfo = new ClassInfo(cr.getSuperName(), cr.getInterfaces());
try{
in.close();
}
catch (Throwable ignore){}
return classInfo;
}
InputStream in = getInputStreamForName(clName, ClassLoader.getSystemClassLoader(), false, ".class");
String superClassName = null;
String[] interfaceNames = null;
if (in == null){
try {
Class cClass = Class.forName(clName.replace("/", "."));
superClassName = "java/lang/Object";
if (cClass.getSuperclass() != null) {
superClassName = cClass.getSuperclass().getName();
}
Class[] iclasses = cClass.getInterfaces();
if (iclasses != null) {
interfaceNames = new String[iclasses.length];
for (int i = 0; i < iclasses.length; i++) {
interfaceNames[i] = iclasses[i].getName();
}
}
} catch (ClassNotFoundException e) {
}
}
if (in == null && superClassName == null) {
in = getInputStreamForName(clName, ClassLoader.getSystemClassLoader(), false, ".clazz");
if (in == null) {
if (!ClassLoader.getSystemClassLoader().equals(loader)) {
in = getInputStreamForName(clName, loader, false, ".class");
if (in != null) {
ClassReader cr = new OffsetLabelingClassReader(in);
classInfo = new ClassInfo(cr.getSuperName(), cr.getInterfaces());
try{
in.close();
}
catch (Throwable ignore){}
return classInfo;
} else {
throw new IOException("Can't read class " + clName + " from classloader " + loader);
}
}
throw new IOException("Can't read class " + clName + " from classloader " + loader);
}
}
if (superClassName == null) {
ClassReader cr = new OffsetLabelingClassReader(in);
classInfo = new ClassInfo(cr.getSuperName(), cr.getInterfaces());
try {
in.close();
} catch (Throwable ignore) {
}
}
else{
classInfo = new ClassInfo(superClassName, interfaceNames);
}
return classInfo;
}
/**
*
* @param name
* @param loader
* @param priveleged if false - will try to use doPriveleged() mode
* @return
*/
private static InputStream getInputStreamForName(final String name, final ClassLoader loader, boolean priveleged, final String ext) {
try {
InputStream in = loader.getResourceAsStream(name + ext);
if (in != null) {
return in;
}
} catch (Throwable ignore) {
}
// trying to get class with custom extension(s) mentioned in "jcov.clext" system property
for(String fileExt : CUSTOM_CLASS_FILE_EXTENSIONS) {
try {
InputStream in = loader.getResourceAsStream(name + (fileExt.startsWith(".") ? fileExt : "." + fileExt));
if (in != null) return in;
} catch (Throwable ignore) {}
}
// trying to get class with priveleges
if (!priveleged) {
return AccessController.doPrivileged(new PrivilegedAction<InputStream>() {
public InputStream run() {
return getInputStreamForName(name, loader, true, ext);
}
});
}
return null;
}
private static class ClassInfo{
String superName;
String[] interfaces;
ClassInfo(String superName, String[] interfaces){
this.superName = superName;
this.interfaces = interfaces;
}
public String getSuperName(){
return superName;
}
public String[] getInterfaces(){
return interfaces;
}
}
}
| 13,001 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
StaticInvokeMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/StaticInvokeMethodAdapter.java | /*
* Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import com.sun.tdk.jcov.util.Utils;
import java.util.HashMap;
import java.util.Map;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import static org.objectweb.asm.Opcodes.*;
/*
* This class serves abstract, native method and field access coverage
* functionality for static instrumentation.
* Works inside Instr2 process - at the beginning mapping of whole signatures
* to collector's slots (not CollectDetect slots!) is filled from template - see
* ClassMorph2 for details. Then, if this method adapter finds virtual invocations
* of methods or fields from map, it hits respective slot.
*
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
**/
public class StaticInvokeMethodAdapter extends MethodVisitor {
private final String className;
private final InstrumentationParams params;
// method attributes
private String methName;
private int methAccess;
public static int getInvokeID(String owner, String name, String descr) {
String sig = owner + "." + name + descr;
Integer id = map.get(sig);
if (id != null) {
return id;
}
sig = owner + "." + name;
id = map.get(sig);
if (id != null) {
return id;
}
return -1;
}
public static final Map<String, Integer> map = new HashMap<>();
public StaticInvokeMethodAdapter(MethodVisitor mv, String className,
String methName, int methAccess,
final InstrumentationParams params) {
super(ASMUtils.ASM_API_VERSION, mv);
this.className = className;
this.methName = methName;
this.methAccess = methAccess;
this.params = params;
}
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
if (params.isInstrumentFields() && params.isIncluded(owner) && params.isCallerFilterAccept(className)) {
if (getInvokeID(owner, name, desc) != -1) {
int id = getInvokeID(owner, name, desc);
InsnList il = new InsnList();
il.add(new LdcInsnNode(id));
il.add(new MethodInsnNode(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/Collect", "hit", "(I)V",
false));
il.accept(this);
}
}
super.visitFieldInsn(opcode, owner, name, desc);
}
/**
* Visit the Code Attribute
*/
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
if ((params.isInstrumentAbstract() || params.isInstrumentNative()) &&
params.isIncluded(owner) || params.isCallerFilterAccept(owner)) {
if (getInvokeID(owner, name, desc) != -1) {
int id = getInvokeID(owner, name, desc);
InsnList il = new InsnList();
il.add(new LdcInsnNode(id));
il.add(new MethodInsnNode(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/Collect", "hit", "(I)V",
false));
il.accept(this);
}
}
if (params.isCallerFilterOn()
&& params.isCallerFilterAccept(className)) {
int id = (name + desc).hashCode();
super.visitLdcInsn(id);
super.visitMethodInsn(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/CollectDetect",
"setExpected",
"(I)V", false);
}
if (params.isInnerInvacationsOff() &&
Utils.isAdvanceStaticInstrAllowed(this.className, name)) {
if (!owner.equals("java/lang/Object") && params.isInnerInstrumentationIncludes(className)) {
int id = ( (this.methAccess & ACC_BRIDGE) == 0x0) ? -1 : 0;
super.visitLdcInsn(id);
super.visitMethodInsn(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/CollectDetect",
"setExpected",
"(I)V", false);
}
}
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
@Override
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.IRETURN:
case Opcodes.FRETURN:
case Opcodes.ARETURN:
case Opcodes.LRETURN:
case Opcodes.DRETURN:
case Opcodes.RETURN:
if (params.isInnerInvacationsOff() &&
Utils.isAdvanceStaticInstrAllowed(className, methName/*"<init>"*/)) {
if (!methName.equals("<clinit>")) {
int id = 0;
super.visitLdcInsn(id);
super.visitMethodInsn(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/CollectDetect", "setExpected", "(I)V",
false);
} else {
super.visitMethodInsn(INVOKESTATIC,
"com/sun/tdk/jcov/runtime/CollectDetect", "leaveClinit", "()V",
false);
}
}
break;
default:
break;
}
super.visitInsn(opcode);
}
public static void addID(String className, String name, String descr, int id) {
String sig = className + "." + name + descr;
map.put(sig, id);
}
}
| 6,984 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ForkingMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/ForkingMethodAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.Label;
/**
* ForkingMethodAdapter
*
* @author Robert Field
*/
class ForkingMethodAdapter extends MethodVisitor {
static class DuplicatingAnnotationAdapter extends AnnotationVisitor {
final AnnotationVisitor av1;
final AnnotationVisitor av2;
DuplicatingAnnotationAdapter(final AnnotationVisitor av1, final AnnotationVisitor av2) {
super(ASMUtils.ASM_API_VERSION);
this.av1 = av1;
this.av2 = av2;
}
public void visit(String name, Object value) {
av1.visit(name, value);
av2.visit(name, value);
}
public void visitEnum(String name, String desc, String value) {
av1.visit(name, value);
av2.visit(name, value);
}
public AnnotationVisitor visitAnnotation(String name, String desc) {
AnnotationVisitor rav1 = av1.visitAnnotation(name, desc);
AnnotationVisitor rav2 = av2.visitAnnotation(name, desc);
return new DuplicatingAnnotationAdapter(rav1, rav2);
}
public AnnotationVisitor visitArray(String name) {
AnnotationVisitor rav1 = av1.visitArray(name);
AnnotationVisitor rav2 = av2.visitArray(name);
return new DuplicatingAnnotationAdapter(rav1, rav2);
}
public void visitEnd() {
av1.visitEnd();
av2.visitEnd();
}
}
/**
* The {@link MethodVisitor} to which this adapter delegates calls.
*/
protected MethodVisitor mv1;
protected MethodVisitor mv2;
/**
* Constructs a new {@link ForkingMethodAdapter} object.
*
* @param mv1 the first code visitor to which this adapter must delegate calls.
* @param mv2 the second code visitor to which this adapter must delegate calls.
*/
public ForkingMethodAdapter(final MethodVisitor mv1, final MethodVisitor mv2) {
super(ASMUtils.ASM_API_VERSION);
this.mv1 = mv1;
this.mv2 = mv2;
}
public AnnotationVisitor visitAnnotationDefault() {
AnnotationVisitor av1 = mv1.visitAnnotationDefault();
AnnotationVisitor av2 = mv2.visitAnnotationDefault();
return new DuplicatingAnnotationAdapter(av1, av2);
}
public AnnotationVisitor visitAnnotation(
final String desc,
final boolean visible) {
AnnotationVisitor av1 = mv1.visitAnnotation(desc, visible);
AnnotationVisitor av2 = mv2.visitAnnotation(desc, visible);
return new DuplicatingAnnotationAdapter(av1, av2);
}
public AnnotationVisitor visitParameterAnnotation(
final int parameter,
final String desc,
final boolean visible) {
AnnotationVisitor av1 = mv1.visitParameterAnnotation(parameter, desc, visible);
AnnotationVisitor av2 = mv2.visitParameterAnnotation(parameter, desc, visible);
return new DuplicatingAnnotationAdapter(av1, av2);
}
public void visitAttribute(final Attribute attr) {
mv1.visitAttribute(attr);
mv2.visitAttribute(attr);
}
public void visitCode() {
mv1.visitCode();
mv2.visitCode();
}
public void visitFrame(
final int type,
final int nLocal,
final Object[] local,
final int nStack,
final Object[] stack) {
mv1.visitFrame(type, nLocal, local, nStack, stack);
mv2.visitFrame(type, nLocal, local, nStack, stack);
}
public void visitInsn(final int opcode) {
mv1.visitInsn(opcode);
mv2.visitInsn(opcode);
}
public void visitIntInsn(final int opcode, final int operand) {
mv1.visitIntInsn(opcode, operand);
mv2.visitIntInsn(opcode, operand);
}
public void visitVarInsn(final int opcode, final int var) {
mv1.visitVarInsn(opcode, var);
mv2.visitVarInsn(opcode, var);
}
public void visitTypeInsn(final int opcode, final String desc) {
mv1.visitTypeInsn(opcode, desc);
mv2.visitTypeInsn(opcode, desc);
}
public void visitFieldInsn(
final int opcode,
final String owner,
final String name,
final String desc) {
mv1.visitFieldInsn(opcode, owner, name, desc);
mv2.visitFieldInsn(opcode, owner, name, desc);
}
public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc,
final boolean isInterface) {
mv1.visitMethodInsn(opcode, owner, name, desc, isInterface);
mv2.visitMethodInsn(opcode, owner, name, desc, isInterface);
}
public void visitJumpInsn(final int opcode, final Label label) {
mv1.visitJumpInsn(opcode, label);
mv2.visitJumpInsn(opcode, label);
}
public void visitLabel(final Label label) {
mv1.visitLabel(label);
mv2.visitLabel(label);
}
public void visitLdcInsn(final Object cst) {
mv1.visitLdcInsn(cst);
mv2.visitLdcInsn(cst);
}
public void visitIincInsn(final int var, final int increment) {
mv1.visitIincInsn(var, increment);
mv2.visitIincInsn(var, increment);
}
public void visitTableSwitchInsn(
final int min,
final int max,
final Label dflt,
final Label labels[]) {
mv1.visitTableSwitchInsn(min, max, dflt, labels);
mv2.visitTableSwitchInsn(min, max, dflt, labels);
}
public void visitLookupSwitchInsn(
final Label dflt,
final int keys[],
final Label labels[]) {
mv1.visitLookupSwitchInsn(dflt, keys, labels);
mv2.visitLookupSwitchInsn(dflt, keys, labels);
}
public void visitMultiANewArrayInsn(final String desc, final int dims) {
mv1.visitMultiANewArrayInsn(desc, dims);
mv2.visitMultiANewArrayInsn(desc, dims);
}
public void visitTryCatchBlock(
final Label start,
final Label end,
final Label handler,
final String type) {
mv1.visitTryCatchBlock(start, end, handler, type);
mv2.visitTryCatchBlock(start, end, handler, type);
}
public void visitLocalVariable(
final String name,
final String desc,
final String signature,
final Label start,
final Label end,
final int index) {
mv1.visitLocalVariable(name, desc, signature, start, end, index);
mv2.visitLocalVariable(name, desc, signature, start, end, index);
}
public void visitLineNumber(final int line, final Label start) {
mv1.visitLineNumber(line, start);
mv2.visitLineNumber(line, start);
}
public void visitMaxs(final int maxStack, final int maxLocals) {
mv1.visitMaxs(maxStack, maxLocals);
mv2.visitMaxs(maxStack, maxLocals);
}
public void visitEnd() {
mv1.visitEnd();
mv2.visitEnd();
}
public void visitInvokeDynamicInsn(String name, String desc,
Handle bsm, Object... bsmArgs) {
mv1.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
mv2.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
}
}
| 8,728 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
MethodAnnotationAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/MethodAnnotationAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.DataMethod;
import com.sun.tdk.jcov.util.Utils;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.MethodVisitor;
/**
* Class that does nothing but collects runtime annotations
*
* @author Dmitry Fazunenko
*/
class MethodAnnotationAdapter extends MethodVisitor {
final DataMethod meth;
@Override
public AnnotationVisitor visitAnnotation(String anno, boolean b) {
meth.addAnnotation(anno);
return super.visitAnnotation(anno, b);
}
MethodAnnotationAdapter(final MethodVisitor mv,
final DataMethod method) {
super(ASMUtils.ASM_API_VERSION, mv);
this.meth = method;
}
}
| 1,949 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
NativeWrappingMethodAdapter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/NativeWrappingMethodAdapter.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.DataMethodEntryOnly;
import com.sun.tdk.jcov.instrument.InstrumentationOptions;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.ClassVisitor;
import static org.objectweb.asm.Opcodes.*;
import org.objectweb.asm.tree.*;
/**
* NativeWrappingMethodAdapter
*
* Write the native method (renamed with a prefix) by simply passing it on to
* the forking adapter. The forking adapter is also handed a MethodNode so that
* it builds a tree representation of the method. Add instrumentation and a call
* to the native to make the wrapper.
*
* @author Robert Field
*/
class NativeWrappingMethodAdapter extends ForkingMethodAdapter {
private final ClassVisitor cv;
private final MethodNode methodNode;
private final DataMethodEntryOnly dataMethod;
private final InstrumentationParams params;
NativeWrappingMethodAdapter(final MethodVisitor mv,
final MethodNode methodNode, final ClassVisitor cv,
final DataMethodEntryOnly dataMethod, final InstrumentationParams params) {
super(mv, methodNode);
this.cv = cv;
this.dataMethod = dataMethod;
this.methodNode = methodNode;
this.params = params;
}
private int computeMaxLocals(String descriptor, int accessFlags) {
int index = 1;
int slot = 0;
if ((accessFlags & ACC_STATIC) == 0) {
++slot;
}
char type;
while ((type = descriptor.charAt(index)) != ')') {
switch (type) {
case 'B': // byte
case 'C': // char
case 'I': // int
case 'S': // short
case 'Z': // boolean
case 'F': // float
case 'L': // object
case '[': // array
++slot;
break;
case 'D': // double
case 'J': // long
slot += 2;
break;
default:
break;
}
index = nextDescriptorIndex(descriptor, index);
}
return slot;
}
private int nextDescriptorIndex(String descriptor, int index) {
switch (descriptor.charAt(index)) {
case 'B': // byte
case 'C': // char
case 'I': // int
case 'S': // short
case 'Z': // boolean
case 'F': // float
case 'D': // double
case 'J': // long
return index + 1;
case 'L': // object
int i = index + 1;
while (descriptor.charAt(i) != ';') {
++i;
}
return i + 1;
case '[': // array
return nextDescriptorIndex(descriptor, index + 1);
default:
break;
}
throw new InternalError("should not reach here");
}
@Override
public void visitEnd() {
super.visitEnd();
InsnList instructions = methodNode.instructions;
String descriptor = methodNode.desc;
// set max locals and max stack
int maxLocals = computeMaxLocals(descriptor, methodNode.access);
methodNode.maxLocals = maxLocals;
methodNode.maxStack = maxLocals + 4;
// set-up args
int slot = 0;
if ((methodNode.access & ACC_STATIC) == 0) {
// "this"
instructions.add(new VarInsnNode(ALOAD, slot));
++slot;
}
char type;
int index;
for (index = 1;
(type = descriptor.charAt(index)) != ')';
index = nextDescriptorIndex(descriptor, index)) {
switch (type) {
case 'B': // byte
case 'C': // char
case 'I': // int
case 'S': // short
case 'Z': // boolean
instructions.add(new VarInsnNode(ILOAD, slot));
++slot;
break;
case 'F': // float
instructions.add(new VarInsnNode(FLOAD, slot));
++slot;
break;
case 'D': // double
instructions.add(new VarInsnNode(DLOAD, slot));
slot += 2;
break;
case 'J': // long
instructions.add(new VarInsnNode(LLOAD, slot));
slot += 2;
break;
case 'L': // object
case '[': // array
instructions.add(new VarInsnNode(ALOAD, slot));
++slot;
break;
default:
break;
}
}
// call the wrapped version
int invokeOp;
if ((methodNode.access & ACC_STATIC) == 0) {
invokeOp = INVOKEVIRTUAL;
} else {
invokeOp = INVOKESTATIC;
}
instructions.add(new MethodInsnNode(invokeOp, dataMethod.getParent().getFullname(),
InstrumentationOptions.nativePrefix + dataMethod.getName(), dataMethod.getVmSignature()));
// return correct type
switch (descriptor.charAt(index + 1)) {
case 'B': // byte
case 'C': // char
case 'I': // int
case 'S': // short
case 'Z': // boolean
instructions.add(new InsnNode(IRETURN));
break;
case 'F': // float
instructions.add(new InsnNode(FRETURN));
break;
case 'D': // double
instructions.add(new InsnNode(DRETURN));
break;
case 'J': // long
instructions.add(new InsnNode(LRETURN));
break;
case 'L': // object
case '[': // array
instructions.add(new InsnNode(ARETURN));
break;
case 'V': // void
instructions.add(new InsnNode(RETURN));
break;
default:
break;
}
String[] exceptions = (String[]) methodNode.exceptions.toArray(new String[0]);
MethodVisitor mvn = cv.visitMethod(
methodNode.access,
methodNode.name,
methodNode.desc,
methodNode.signature,
exceptions);
//instrument wrapper
EntryCodeMethodAdapter ecma = new EntryCodeMethodAdapter(mvn, dataMethod, params);
methodNode.accept(ecma);
}
}
| 7,948 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ClassMorph2.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/instrument/asm/ClassMorph2.java | /*
* Copyright (c) 2014, 2022 Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.instrument.asm;
import com.sun.tdk.jcov.instrument.DataRoot;
import com.sun.tdk.jcov.instrument.InstrumentationParams;
import com.sun.tdk.jcov.io.Reader;
import com.sun.tdk.jcov.util.DebugUtils;
import org.objectweb.asm.*;
import org.objectweb.asm.util.TraceClassVisitor;
/**
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public class ClassMorph2 {
private final InstrumentationParams params;
public ClassMorph2(final InstrumentationParams params, String template) {
this.params = params;
try {
DataRoot root = Reader.readXML(template, true, null);
ClassMorph.fillIntrMethodsIDs(root);
} catch (Throwable t) {
throw new Error(t);
}
}
public boolean isTransformed(String className) {
return className != null
&& !className.startsWith("com/sun/tdk/jcov")
&& !className.startsWith("org/objectweb/asm");
}
public boolean shouldTransform(String className) {
return isTransformed(className)
&& params.isIncluded(className);
}
public byte[] morph(byte[] classfileBuffer, String flushPath) {
ClassReader cr = new ClassReader(classfileBuffer);
String fullname = cr.getClassName();
if (!isTransformed(fullname)) {
return null;
}
if (!shouldTransform(fullname)) {
return null;
}
// Consider manually optimizing out the ClassWriter.COMPUTE_FRAMES
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
boolean shouldFlush = (flushPath != null);
ClassVisitor cv = shouldFlush ? new TraceClassVisitor(cw, DebugUtils.getPrintWriter(fullname, flushPath))
: cw;
cv = new InvokeClassAdapter(cv, params) {
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
MethodVisitor instr = new StaticInvokeMethodAdapter(mv, className, name, access, params);
return instr;
}
};
cr.accept(cv, 0);
return cw.toByteArray();
}
}
| 3,523 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataProcessorSPI.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/DataProcessorSPI.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.processing;
import com.sun.tdk.jcov.tools.ServiceProvider;
/**
* This interface defines the Service Provider Interface (SPI) for the
* <code>DataProcessorFactory</code> class. <p>
*
* @author Dmitry Fazunenko
*/
public interface DataProcessorSPI extends ServiceProvider {
/**
* Creates a data processor.
*
* @return new data processor
*/
public DataProcessor getDataProcessor();
}
| 1,649 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataProcessor.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/DataProcessor.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.processing;
import com.sun.tdk.jcov.instrument.DataRoot;
/**
* Interface for data processors.
* <p/>
* When a format is not supported the corresponding
* <code>process()</code> should throw
* <code>UnsupportedOperationException</code>.
*
* @see DataProcessorSPI
* @author Dmitry Fazunenko
*/
public interface DataProcessor {
/**
* Handles passed JcovFileImage object. It's up to implementator to return
* either the same or new created object.
*
* @param root - data to process
* @return modified data
* @throws ProcessingException - if error occurred while processing
* @throws UnsupportedOperationException - if format is not supported by the
* data processor
*/
public DataRoot process(DataRoot root) throws ProcessingException;
/**
* Implementation that returns input data unmodified.
*/
public final static DataProcessor STUB = new DataProcessor() {
public DataRoot process(DataRoot root) throws ProcessingException {
return root;
}
};
}
| 2,290 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
package-info.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/package-info.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* <p> DataProcessor Service Provider </p> <p> Interface for DataProcessor and
* it's default implementations. </p> <p> DataProcessor allows to pre-process
* (modify) coverage structure before it's processing in tools. </p>
*/
package com.sun.tdk.jcov.processing; | 1,477 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ConveyerProcessor.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/ConveyerProcessor.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.processing;
import com.sun.tdk.jcov.instrument.DataRoot;
import java.util.ArrayList;
import java.util.List;
/**
* A processor that applies other processors in series.
*
* @author Dmitry Fazunenko
*/
public class ConveyerProcessor implements DataProcessor {
private final List<DataProcessor> processors;
/**
* Constructs a processor with an empty set of data processors
*/
public ConveyerProcessor() {
processors = new ArrayList<DataProcessor>();
}
/**
* Adds processor to the list of data processors to be applied.
*
* @param p - processors, if null - nothing will happen
*/
public void add(DataProcessor p) {
if (p != null && !processors.contains(p)) {
processors.add(p);
}
}
/**
* Removes processor from the list of processors to be applied.
*
* @param p - processor, if null - nothing will happen
*/
public void remove(DataProcessor p) {
if (p != null) {
processors.remove(p);
}
}
/**
* Applies all registered processors to the image in order they were added.
*
* @param root - data to process
* @return modified data
* @throws ProcessingException - if one of added processor fail to handle
* data
* @throws UnsupportedOperationException - if format is not supported by any
* of registred data processor
*/
public DataRoot process(DataRoot root) throws ProcessingException {
DataRoot result = root;
for (DataProcessor p : processors) {
result = p.process(result);
}
return result;
}
}
| 2,886 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ProcessingException.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/ProcessingException.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.processing;
/**
* Exception signaling a problem happened while data processing.
*
* @author Dmitry Fazunenko
*/
public class ProcessingException extends Exception {
public ProcessingException(String message) {
super(message);
}
public ProcessingException(String message, Throwable cause) {
super(message, cause);
}
public ProcessingException(Throwable cause) {
super(cause);
}
}
| 1,667 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
StubSpi.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/StubSpi.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.processing;
import com.sun.tdk.jcov.tools.EnvHandler;
/**
* Stub implementation of DataProcessorFactorySpi
*
* @author Dmitry Fazunenko
*/
public class StubSpi implements DataProcessorSPI {
/**
* @return Data processor returning input data unmodified
*/
public DataProcessor getDataProcessor() {
return DataProcessor.STUB;
}
public void extendEnvHandler(final EnvHandler handler) {
}
public int handleEnv(EnvHandler handler) {
return 0;
}
} | 1,735 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DataProcessorFactory.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/DataProcessorFactory.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.processing;
/**
*
* @author Dmitry Fazunenko
*/
public class DataProcessorFactory {
/**
* Default SPI to be used.
*/
public static final String DEFAULT_SPI =
// "com.sun.tdk.jcov.processing.fx.FXDataProcessorFactorySpi";
"com.sun.tdk.jcov.processing.DefaultDataProcessorSpi";
/**
* Property name to specify DataProcessorFactorySpi class name
*/
public static final String PROP_NAME = "dataprocessor.spi";
private DataProcessorSPI spi = null;
private DataProcessorFactory(String spiClassName) {
if (spiClassName == null) {
spi = null;
} else {
try {
Class spiClass = Class.forName(spiClassName);
spi = (DataProcessorSPI) spiClass.newInstance();
} catch (Exception e) {
throw new Error("Cannot create an instance of "
+ " DataProcessorFactorySpi: " + e);
}
}
}
/**
* Returns DataProcessorFactory instance. DataProcessorFactory uses
* DataProcessorFactorySpi to get class member filter which is initialized
* during the first call of this method. Name of SPI class is taken from the
* <code>dataprocessor.spi</code> system property. If the property is not
* set, the default value will be used instead.
*
* @return factory instance
* @throws Error if instance of DataProcessorFactory cannot be created.
*
*/
public static DataProcessorFactory getInstance() {
String spiClassName = System.getProperty(PROP_NAME);
if (spiClassName == null) {
spiClassName = DEFAULT_SPI;
} else if ("none".equalsIgnoreCase(spiClassName)) {
spiClassName = StubSpi.class.getName();
}
return new DataProcessorFactory(spiClassName);
}
/**
* Returns data processor. Never returns null.
*/
public DataProcessor getDataProcessor() {
return spi == null ? DataProcessor.STUB : spi.getDataProcessor();
}
}
| 3,292 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
CombinerDataProcessor.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/CombinerDataProcessor.java | /*
* Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.processing;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.instrument.DataMethod;
import com.sun.tdk.jcov.instrument.DataMethodEntryOnly;
import com.sun.tdk.jcov.instrument.DataPackage;
import com.sun.tdk.jcov.instrument.DataRoot;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Processor, that combines classes derived from the same sources.
*
* @author Dmitry Fazunenko
*/
public class CombinerDataProcessor implements DataProcessor {
public DataRoot process(DataRoot root) throws ProcessingException {
HashMap<String, ArrayList<DataClass>> classesMap =
new HashMap<String, ArrayList<DataClass>>();
DataRoot result = new DataRoot(root.getParams());
result.setScaleOpts(root.getScaleOpts());
// building map: scr --> cls1, cls2, ...
List<DataPackage> allPkg = root.getPackages();
for (DataPackage pkg : allPkg) {
for (Iterator<DataClass> it = pkg.getClasses().iterator(); it.hasNext();) {
DataClass cls = it.next();
String srcName = cls.getSource();
if (srcName != null) {
String key = pkg.getName() + '/' + srcName;
ArrayList<DataClass> srcClasses = classesMap.get(key);
if (srcClasses == null) {
srcClasses = new ArrayList<DataClass>();
classesMap.put(key, srcClasses);
}
srcClasses.add(cls);
} else {
result.addClass(cls); // src == null
}
}
}
// combining classes derived from the same source
for (String key : classesMap.keySet()) {
ArrayList<DataClass> toMerge = classesMap.get(key);
if (toMerge.size() == 1) {
// nothing to combine: one class in the source
result.addClass(toMerge.get(0)); // just one class
} else {
int k = key.indexOf(".");
String mainClassName = k > 0 ? key.substring(0, k) : key;
DataClass cls = findMainClazz(toMerge, mainClassName);
// it's expected, the main class is always the first in the list
DataClass newClass = cls.clone(result.rootId());
k = mainClassName.lastIndexOf("/");
if (k > 0) {
mainClassName = mainClassName.substring(k + 1);
}
for (DataClass c : toMerge) {
if (c == cls) {
continue; // skip mainClass
}
String clzName = c.getName();
int j = clzName.lastIndexOf("/");
if (j >= 0) {
clzName = clzName.substring(j + 1);
}
String prefix = createPrefix(clzName, mainClassName);
for (DataMethod m : c.getMethods()) {
DataMethod nm = m.clone(newClass, m.getAccess(), prefix + m.getName());
// for -type=method methods exist witout blocks and branches
if (nm instanceof DataMethodEntryOnly) {
nm.setCount(m.getCount());
((DataMethodEntryOnly) nm).setScale(m.getScale());
}
// new created method will be added to the newClass
}
for (DataField f : c.getFields()) {
f.clone(newClass, f.getAccess(), prefix + f.getName());
}
}
result.addClass(newClass);
}
}
return result;
}
/**
* Finds the main class for the sources which name equals to the source
*
* @param toMerge
* @param mainClassName
* @return
*/
protected DataClass findMainClazz(ArrayList<DataClass> toMerge, String mainClassName) {
for (DataClass c : toMerge) {
if (mainClassName.equals(c.getFullname())) {
return c;
}
}
return toMerge.get(0);
}
/**
* Forms the prefix for a given class to be used in the report. This
* implementation uses empty prefix for the main class, and a class name
* precided with the "!" for nested classes, and precided with "%" for
* classes defined outside the main one.
*
* This method can be overrided to alter the rules above.
*
* @param className - class name to generate prefix for
* @param mainClassName - the main class of the source
* @return prefix
*/
protected String createPrefix(String className, String mainClassName) {
if (className.equals(mainClassName)) {
return "";
} else if (className.startsWith(mainClassName + "$")) {
return className.substring(className.indexOf("$")) + ".";
} else {
return "~" + className + ".";
}
}
} | 6,425 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
DefaultDataProcessorSPI.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/processing/DefaultDataProcessorSPI.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.processing;
import com.sun.tdk.jcov.tools.EnvHandler;
import com.sun.tdk.jcov.tools.EnvServiceProvider;
/**
* Provider of DataProcessor used by default.
*
* @author Dmitry Fazunenko
*/
public class DefaultDataProcessorSPI implements DataProcessorSPI, EnvServiceProvider {
public DataProcessor getDataProcessor() {
return new CombinerDataProcessor();
}
public void extendEnvHandler(final EnvHandler handler) {
}
public int handleEnv(EnvHandler handler) {
return 0;
}
} | 1,748 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
MemberFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/filter/MemberFilter.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.filter;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.instrument.DataMethod;
/**
* Interface for a class that sets acceptance criteria for classes and class
* members.
*
* For both legacy and modern JCov data representation formats.
*
* @author Dmitry Fazunenko
*/
public interface MemberFilter {
/**
* The filter that accepts everything.
*/
public static MemberFilter ACCEPT_ALL = new AcceptAll();
/**
* Returns true if a class is acceptable, false otherwise.
*/
public boolean accept(DataClass clz);
/**
* Returns true if a method is acceptable, false otherwise.
*/
public boolean accept(DataClass clz, DataMethod m);
/**
* Returns true if a field is acceptable, false otherwise.
*/
public boolean accept(DataClass clz, DataField f);
/**
* Implementation accepting everthing
*/
final static class AcceptAll implements MemberFilter {
public boolean accept(DataClass clz) {
return true;
}
public boolean accept(DataClass clz, DataMethod m) {
return true;
}
public boolean accept(DataClass clz, DataField f) {
return true;
}
@Override
public String toString() {
return "AcceptAll filter";
}
}
}
| 2,628 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
package-info.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/filter/package-info.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* <p> MemberFilter Service Provider. </p> <p> Interface for MemberFilter and
* it's default implementations. </p> <p> MemberFilter allows to select parts of
* coverage data which should be processed in JCov tools. </p>
*/
package com.sun.tdk.jcov.filter; | 1,469 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
FilterFactory.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/filter/FilterFactory.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.filter;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.instrument.DataMethod;
/**
* <b>FilterFactory</b> factory is used by to instantiate member filter. <p>
* This class uses a provider-based architecture. To create a FilterFactory call
* the static getInstance() methods. <p> Once a FilterFactory object is created,
* filters can be obtained by calling the getMemberFilter() method
*
* @author Dmitry Fazunenko
* @author Sergey Borodin
*/
public class FilterFactory {
// candidate to remove
private FilterSpi spi = null;
private FilterFactory(String spiClassName) {
if (spiClassName == null) {
spi = null;
} else {
try {
Class spiClass = Class.forName(spiClassName);
spi = (FilterSpi) spiClass.newInstance();
} catch (Exception e) {
throw new Error("Cannot create an instance of "
+ "FilterFactorySpi: " + e);
}
}
}
/**
* Returns FilterFactory instance. FilterFactory uses FilterFactorySpi to
* get class member filter which is initialized during the first call of
* this method.
*
* @param spiClassName name of spi class
* @return factory instance
* @throws Error if instance of FilterFactory cannot be created.
*
*/
public static FilterFactory getInstance(String spiClassName) {
return new FilterFactory(spiClassName);
}
/**
* Returns member filter. Never returns null.
*/
public MemberFilter getMemberFilter() {
MemberFilter filter = spi == null ? MemberFilter.ACCEPT_ALL
: new DelegateFilter(spi);
return filter;
}
final class DelegateFilter implements MemberFilter {
private String spiName;
private MemberFilter delegate;
DelegateFilter(FilterSpi spi) {
spiName = spi.getClass().getName();
delegate = spi.getFilter();
}
public boolean accept(DataClass clz) {
if (delegate == null) {
throw new UnsupportedOperationException("Trying to filter using "
+ spiName);
} else {
return delegate.accept(clz);
}
}
public boolean accept(DataClass clz, DataMethod m) {
if (delegate == null) {
throw new UnsupportedOperationException("Trying to filter"
+ " modern data using " + spiName);
} else {
return delegate.accept(clz, m);
}
}
public boolean accept(DataClass clz, DataField f) {
if (delegate == null) {
throw new UnsupportedOperationException("Trying to filter"
+ " modern data using " + spiName);
} else {
return delegate.accept(clz, f);
}
}
@Override
public String toString() {
return delegate == null ? spiName + " filter" : delegate.toString();
}
}
}
| 4,382 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
FilterSpi.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/filter/FilterSpi.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.filter;
import com.sun.tdk.jcov.tools.ServiceProvider;
/**
* This interface defines the Service Provider Interface (SPI) for the
* <code>FilterFactory</code> class. <p>
*
* @author Dmitry Fazunenko
* @author Sergey Borodin
*
*/
public interface FilterSpi extends ServiceProvider {
/**
* Creates a class member filter.
*
* @return new filter, or null, if not supported
*/
public MemberFilter getFilter();
}
| 1,676 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
AcceptAllSpi.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/filter/AcceptAllSpi.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.filter;
/**
* Implementation that returns filter accpeting everything.
*
* @author Dmitry Fazunenko
*/
public class AcceptAllSpi implements FilterSpi {
public AcceptAllSpi() {
}
public MemberFilter getFilter() {
return MemberFilter.ACCEPT_ALL;
}
}
| 1,511 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
ConveyerFilter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/filter/ConveyerFilter.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.filter;
import com.sun.tdk.jcov.instrument.DataClass;
import com.sun.tdk.jcov.instrument.DataField;
import com.sun.tdk.jcov.instrument.DataMethod;
import java.util.ArrayList;
import java.util.List;
/**
* A filter that applies other filters in series.
*
* @author Dmitry Fazunenko
*/
public class ConveyerFilter implements MemberFilter {
private final List<MemberFilter> filters;
/**
* Constructs a filter with an empty set of filters
*/
public ConveyerFilter() {
filters = new ArrayList<MemberFilter>();
}
/**
* Adds filter to the list of filters to be applied.
*
* @param f - filter, if null - nothing will happen
*/
public void add(MemberFilter f) {
if (f != null && !filters.contains(f)) {
filters.add(f);
}
}
/**
* Removes filter from the list of filters to be applied.
*
* @param f - filter, if null - nothing will happen
*/
public void remove(MemberFilter f) {
if (f != null) {
filters.remove(f);
}
}
/**
* Walks from the list of filters in the order they were added and applies
* them one by one.
*
* @param clz - class to check
* @return true if either the class is accepted by all filters or none of
* filters were added.
*/
public boolean accept(DataClass clz) {
for (MemberFilter f : filters) {
if (!f.accept(clz)) {
return false;
}
}
return true;
}
/**
* Walks from the list of filters in the order they were added and applies
* them one by one.
*
* @param clz - class of method
* @param m - method to check
* @return true if either the method of the class is accepted by all filters
* or none of filters were added.
*/
public boolean accept(DataClass clz, DataMethod m) {
for (MemberFilter f : filters) {
if (!f.accept(clz, m)) {
return false;
}
}
return true;
}
/**
* Walks from the list of filters in the order they were added and applies
* them one by one.
*
* @param clz - class of field
* @param fld - field to check
* @return true if either class the field of the class accepted by all
* filters or none of filters were added.
*/
public boolean accept(DataClass clz, DataField fld) {
for (MemberFilter f : filters) {
if (!f.accept(clz, fld)) {
return false;
}
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Conveyer filter: ");
for (MemberFilter f : filters) {
sb.append(f.toString()).append(" ");
}
return sb.toString();
}
}
| 4,089 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
AbstractUniversalInstrumenter.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/insert/AbstractUniversalInstrumenter.java | /*
* Copyright (c) 2014, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.insert;
import com.sun.tdk.jcov.instrument.asm.OverriddenClassWriter;
import com.sun.tdk.jcov.util.Utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import static com.sun.tdk.jcov.util.Utils.FILE_TYPE;
import static com.sun.tdk.jcov.util.Utils.FILE_TYPE.*;
import static com.sun.tdk.jcov.util.Utils.isClassFile;
/**
* The class is resposible to deal with class files and hierarchies of files, such as directories, jars, zips, modules.
* The actual logic of bytecode instrumentation is left for subclasses of this class.
* @see #instrument(byte[], int)
* @see #finishWork()
* @author Dmitry Fazunenko
* @author Alexey Fedorchenko
*/
public abstract class AbstractUniversalInstrumenter {
private String INSTR_FILE_SUFF = "i";
private int fileCount = 0; // counter of processed files
private int classCount = 0; // counter of processed classes
private int iClassCount = 0; // counter of successfully instrumented classes
private static final Logger logger;
static {
Utils.initLogger();
logger = Logger.getLogger(AbstractUniversalInstrumenter.class.getName());
}
/**
* buffer for reading class data (either from a class file or from an
* archive)
*/
protected byte[] classBuf = new byte[32 * 1024];
/**
* whether to overwrite files with their instrumented versions
*/
protected boolean overwrite;
/**
* whether to save instrumentation results or not
*/
protected boolean readOnly;
public AbstractUniversalInstrumenter(boolean overwrite) {
this(overwrite, false);
}
/**
* <p> Creates AbstractUniversalInstrumenter instance </p>
*
* @param overwrite Overwrite existing binary
* @param readOnly Do not produce instrumented binaries (template generation
* purposes)
*/
public AbstractUniversalInstrumenter(boolean overwrite, boolean readOnly) {
this.overwrite = overwrite;
this.readOnly = readOnly;
}
/**
* constructs instrumented file name by inserting
* InstrConstants.INSTR_FILE_SUFF string before the first character of the
* extension
*
* @param name file name to construct new name for
* @return constructed name
*/
protected String makeInstrumentedFileName(String name) {
int dotInd = name.lastIndexOf('.');
if (dotInd <= 0) {
logger.log(Level.SEVERE, "Invalid classfile name: ''{0}''", name);
}
return name.substring(0, dotInd) + "." + INSTR_FILE_SUFF + name.substring(dotInd + 1, name.length());
}
/**
* ensures that the class data buffer is capable of storing the specified
* number of bytes
*
* @param length number of bytes to be stored
* @param copy_old_buf preserve contents of the buffer if it must be
* reallocated
*/
private void ensureClassBufLength(int length, boolean copy_old_buf) {
if (classBuf.length >= length) {
return;
}
byte[] tmp_buf = new byte[length + length / 2];
if (copy_old_buf) {
System.arraycopy(classBuf, 0, tmp_buf, 0, classBuf.length);
}
classBuf = tmp_buf;
}
/**
* instruments specified class file
*
* @param f class file to be instrumented
* @return whether the file represented by f has been instrumented
*/
protected boolean processClassFile(File f, File outFile) throws IOException {
String fname = f.getPath();
// to suppress verbosity: logger.log(Level.INFO, "Instrumenting classfile ''{0}''...", fname);
boolean instredFine = true;
int classLength = (int) f.length();
if (f.getName().equals("module-info.class")){
return true;
}
ensureClassBufLength(classLength, false);
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
logger.log(Level.SEVERE, " File not found - skipped", e);
return false;
}
try {
fis.read(classBuf, 0, classLength); // read in class data
fis.close();
} catch (IOException e) {
logger.log(Level.SEVERE, " Error reading '" + fname + "' - skipped", e);
return false;
}
byte[] outBuf = null;
try {
if (f.length() < 4) {
if (f.length() == 0) {
logger.log(Level.SEVERE, " Error reading data from ''{0}'': File is empty\n - skipped",
fname);
instredFine = false;
} else {
logger.log(Level.SEVERE, " Error reading data from ''{0}'': File is too small ({1}) - skipped",
new Object[]{fname, f.length()});
instredFine = false;
}
} else {
outBuf = instrument(classBuf, classLength); // instrument the class
// System.out.println(f + " " + classBuf.length + " " + (outBuf == null ? "null" : outBuf.length));
}
} catch (IOException e) {
logger.log(Level.SEVERE, " Error reading data from '" + fname + "' - skipped", e);
instredFine = false;
} catch (NullPointerException e) {
logger.log(Level.SEVERE, " Error reading data from '" + fname + "' - skipped", e);
instredFine = false;
} catch (Exception e) {
logger.log(Level.SEVERE, " Error instrumenting '" + fname + "' - skipped", e);
instredFine = false;
}
if (outBuf == null) {
// class can't be/is already instrumented
instredFine = false;
outBuf = classBuf;
} else {
classLength = outBuf.length;
}
if (!readOnly) {
// construct instrumented class file name
if (outFile == null) {
outFile = f;
f.delete();
}
// create "super" directories if necessary
String parentName = outFile.getParent();
if (parentName != null) {
File parent = new File(parentName);
if (!parent.exists()) {
parent.mkdirs();
}
}
// write instrumented classfile
FileOutputStream fos = new FileOutputStream(outFile);
fos.write(outBuf, 0, classLength);
fos.close();
}
return instredFine;
}
/**
* instruments all class files in the specified directory and its
* subdirectories.
*
* @param dir directory to be instrumented
*/
protected void processClassDir(File dir, File outDir) throws IOException {
String[] entries = dir.list();
Arrays.sort(entries);
for (int i = 0; i < entries.length; i++) {
File f = new File(dir.getPath() + File.separator + entries[i]);
if (f.isDirectory()) {
processClassDir(f, new File(outDir, entries[i]));
} else {
fileCount++;
if (FILE_TYPE.hasExtension(f.getPath(), CLASS)) {
classCount++;
if (processClassFile(f, new File(outDir, entries[i]))) {
iClassCount++;
}
}
}
}
}
/**
* instruments classes in specified jar- or zip-archive
*
* @param arc archive to be instrumented
* @param rtPath runtime jar to me implanted. Ignored when null
*/
protected void processArc(File arc, File outArc, String rtPath) {
logger.log(Level.INFO, " - Instrumenting archive ''{0}''...", arc);
String outFilename = outArc == null ? makeInstrumentedFileName(arc.getPath()) :
outArc.getPath() + File.separator + arc.getName();
logger.log(Level.CONFIG, " Output archive ''{0}''", outFilename);
if (rtPath != null) {
logger.log(Level.CONFIG, " RT to implant: ''{0}''", rtPath);
}
CRC32 crc32 = new CRC32();
ZipInputStream in;
try {
in = new ZipInputStream(new BufferedInputStream(new FileInputStream(arc)));
} catch (Exception ex) {
logger.log(Level.SEVERE, " Error opening archive '" + arc.getPath() + "'", ex);
return;
}
ZipOutputStream out = null;
// construct instrumented archive name and create the file
File outFile = new File(outFilename);
if (!readOnly) {
try {
out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
} catch (IOException ex) {
logger.log(Level.SEVERE, " Error creating output archive '" + outFilename + "'", ex);
}
}
while (true) {
// cycle by all entries in the archive
ZipEntry e0 = null; // last read entry
try {
e0 = in.getNextEntry();
} catch (IOException ex) {
logger.log(Level.SEVERE, " Error reading archive entry in '" + arc.getPath() + "'", ex);
}
if (e0 == null) {
// are there any remaining entries?
break;
}
String ename = e0.getName();
boolean isDir = e0.isDirectory();
if (!isDir) {
fileCount++;
}
int fileLength = (int) e0.getSize();
try {
if (fileLength >= 0) {
// is length of the entry known?
ensureClassBufLength(fileLength, false);
// in.read(byte[],int,int) has a bug in JDK1.1.x - using in.read()...
for (int i = 0; i < fileLength; classBuf[i++] = (byte) in.read()) {
}
in.read(classBuf, 0, fileLength);
} else {
// no - read until the end of stream is encountered
int i = 0;
for (;; i++) {
int b = in.read();
if (b < 0) {
break;
}
ensureClassBufLength(i + 1, true); // make sure classBuf is big enough
classBuf[i] = (byte) b;
}
fileLength = i;
}
} catch (IOException ex) {
logger.log(Level.SEVERE, " Error reading archive entry '" + ename + "' in '" + arc.getPath() + "' - skipped", ex);
}
byte[] res;
boolean isClass = ename.endsWith(CLASS.getExtension()) && !isDir;
if (isClass) {
// does the entry represent a class file?
classCount++;
logger.log(Level.INFO, " Instrumenting ''{0}''...", ename);
try {
res = instrument(classBuf, fileLength); // try to instrument it
} catch (IOException ex) {
logger.log(Level.SEVERE, " Error reading archive entry '" + ename + "' in '" + arc.getPath() + "' - skipped", ex);
res = null;
} catch (Exception ex) {
logger.log(Level.SEVERE, " Error instrumenting archive entry '" + ename + "' in '" + arc.getPath() + "' - skipped", ex);
res = null;
}
} else {
// no - will write the buffer unchanged
res = classBuf;
logger.log(Level.INFO, " Storing ''{0}''...", ename);
}
if (!readOnly) {
ZipEntry e1 = new ZipEntry(ename); // entry to be written to the resulting archive
e1.setSize(fileLength);
e1.setMethod(e0.getMethod());
e1.setExtra(e0.getExtra());
e1.setComment(e0.getComment());
long crc = e0.getCrc();
if (crc >= 0) {
e1.setCrc(crc);
}
if (res != null && isClass) {
// have the class been instrumented?
if (res.length > 1) {
iClassCount++;
if (e0.getCrc() != -1) {
// update CRC if needed
crc32.reset();
crc32.update(res);
e1.setCrc(crc32.getValue());
}
fileLength = res.length; // set new length
e1.setSize(fileLength);
} else {
if (res.length == 1 && res[0] == (byte) 'P') {
logger.log(Level.WARNING, " skipped: first pass native preview");
}
if (res.length == 1 && res[0] == (byte) 'F') {
logger.log(Level.WARNING, " skipped: filtered out");
}
res = classBuf;
}
} else {
// no - will write the buffer unchanged
res = classBuf;
if (!isClass) {
logger.log(Level.FINE, " ''{0}'' - not instrumented (not a class)", ename);
} else {
// logger.log(Level.WARNING, " ''{0}'' - not instrumented", ename);
}
}
try {
out.putNextEntry(e1); // write the entry to the resulting archive
out.write(res, 0, fileLength); // write actual entry data as well
out.closeEntry();
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error adding archive entry '" + ename + "' to '" + outFilename + "' - skipped", ex);
}
}
}
// all entries read/processed/written - close input stream
try {
in.close();
} catch (IOException ex) {
}
try {
// coping JCovRT classes to the output jar
if (rtPath != null) {
logger.log(Level.INFO, " Adding saver library...");
File rt = new File(rtPath);
if (!rt.exists()) {
throw new IOException("Runtime file doesn't exist " + rt);
}
if (!rt.isFile() || !FILE_TYPE.hasExtension(rt.getName(), JAR, ZIP)) {
throw new IOException("Malformed runtime archive " + rt);
}
ZipInputStream rtIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(rt)));
outer:
while (true) {
ZipEntry e0 = rtIn.getNextEntry();
if (e0 == null) {
// are there any remaining entries?
break;
}
String ename = e0.getName();
if (ename.startsWith("META-INF")) {
continue;
}
int fileLength = (int) e0.getSize();
if (fileLength >= 0) {
// is length of the entry known?
ensureClassBufLength(fileLength, false);
// in.read(byte[],int,int) has a bug in JDK1.1.x - using in.read()...
for (int i = 0; i < fileLength; classBuf[i++] = (byte) rtIn.read());
rtIn.read(classBuf, 0, fileLength);
} else {
// no - read until the end of stream is encountered
int i = 0;
for (;; i++) {
int b = rtIn.read();
if (b < 0) {
break;
}
ensureClassBufLength(i + 1, true); // make sure classBuf is big enough
classBuf[i] = (byte) b;
}
fileLength = i;
}
ZipEntry e1 = new ZipEntry(ename); // entry to be written to the resulting archive
e1.setSize(fileLength);
e1.setMethod(e0.getMethod());
e1.setExtra(e0.getExtra());
e1.setComment(e0.getComment());
long crc = e0.getCrc();
if (crc >= 0) {
e1.setCrc(crc);
}
ZipInputStream inJar = new ZipInputStream(new BufferedInputStream(new FileInputStream(arc)));
try {
ZipEntry checking;
while (true) {
checking = inJar.getNextEntry();
if (checking == null) {
break;
}
if (checking.getName().equals(e1.getName())) {
if (checking.getSize() != e1.getSize()) {
// logger.log(Level.WARNING, "Output jar contains file {0} that was found in runtime jar but files sizes differ, skipping",
// checking.getName());
} else {
// logger.log(Level.INFO, "Output jar contains file {0} that was found in runtime jar, skipping",
// checking.getName());
}
inJar.close();
continue outer;
}
}
} catch (EOFException e) {
// logger.log(Level.SEVERE);
} finally {
inJar.close();
}/**/
// logger.log(Level.INFO, "Adding runtime file {0} to output jar {1}", new Object[]{e1.getName, jar.getName()})
try {
out.putNextEntry(e1); // write the entry to the resulting archive
} catch (ZipException e) {
if (!e.getMessage().startsWith("duplicate entry")) {
throw e;
}
}
out.write(classBuf, 0, fileLength); // write actual entry data as well
out.closeEntry();
}
rtIn.close();
}
if (out != null) {
out.finish();
out.close();
}
} catch (Throwable ex) {
logger.log(Level.SEVERE, "Error processing archive '" + arc.getPath() + "'", ex);
outFile.delete();
return;
}
if (!readOnly && outArc == null && overwrite) {
if (!arc.delete()) {
logger.log(Level.WARNING, " Can''t remove initial JAR file ''{0}''",
arc.getAbsolutePath());
}
if (!outFile.renameTo(arc)) {
logger.log(Level.WARNING, " Can''t rename result JAR file ''{0}' to ''{1}''. Please move manually",
new Object[]{outFile.getAbsolutePath(), arc.getAbsolutePath()});
}
}
}
public void instrument(String arg) throws IOException {
instrument(new File(arg), null, null, false);
}
/**
* determines what kind of object is represented by given path and invokes
* appropriate methods to instrument the object
*
* @param arg path to a class file, zip/jar archive or a directory
*/
public void instrument(File arg, File outDir) throws IOException {
instrument(arg, outDir, null, false);
}
public void instrument(File arg, File outDir, String rtPath) throws IOException {
instrument(arg, outDir, rtPath, false);
}
public void instrument(File instrumentingPath, File destinationPath, String rtPath, boolean recursive) throws IOException {
instrument(instrumentingPath, destinationPath, rtPath, null, recursive);
}
/**
* <p> Determines what kind of object is represented by given path and
* invokes appropriate methods to instrument the object </p>
*
* @param instrumentingPath path to a class file, zip/jar archive or a
* directory
* @param destinationPath output path. Initial file is replaced in case if
* null
* @param rtPath path to runtime jar. Ignored if null
* @param recursive insrument method will recurse through initial directory
* if true instrumenting each file in the tree
*/
public void instrument(File instrumentingPath, File destinationPath,
String rtPath, ArrayList<String> rtClassDirTargets,
boolean recursive) throws IOException {
fileCount = 0;
classCount = 0;
iClassCount = 0;
if (!instrumentingPath.exists()) {
logger.log(Level.WARNING, "Path ''{0}'' doesn''t exist - skipped", instrumentingPath);
return;
}
boolean isClassFile = false;
if (instrumentingPath.isDirectory()) {
if (destinationPath == null) {
destinationPath = instrumentingPath;
}
if (recursive) {
Utils.addToClasspath(instrumentingPath);
logger.log(Level.FINE, "Scanning directory ''{0}''...", instrumentingPath);
File[] entries = instrumentingPath.listFiles();
Arrays.sort(entries);
for (int i = 0; i < entries.length; i++) {
destinationPath.mkdir();
instrument(entries[i], new File(destinationPath, entries[i].getName()), rtPath, rtClassDirTargets, recursive);
}
} else {
logger.log(Level.INFO, "Instrumenting directory ''{0}''...", instrumentingPath);
processClassDir(instrumentingPath, destinationPath);
if (rtPath != null) {
if (destinationPath != null) {
unjarRT(rtPath, destinationPath);
} else {
unjarRT(rtPath, instrumentingPath);
}
}
}
} else if ( FILE_TYPE.hasExtension(instrumentingPath.getName(), JAR, ZIP, WAR) ) {
// initially instrument(jar, toJar) meant create instrumented "toJar/jar". But in recursive mode it should be just "toJar".
if (rtClassDirTargets == null || rtClassDirTargets.contains(instrumentingPath.getPath())) {
if (recursive) {
processArc(instrumentingPath, destinationPath.getParentFile(), rtPath);
} else {
processArc(instrumentingPath, destinationPath, rtPath);
}
} else {
if (recursive) {
processArc(instrumentingPath, destinationPath.getParentFile(), null);
} else {
processArc(instrumentingPath, destinationPath, null);
}
}
} else if (instrumentingPath.getName().equals("modules")) {
instrumentModulesFile(instrumentingPath, destinationPath);
} else if (isClassFile(instrumentingPath.getName())) {
if (destinationPath == null) {
destinationPath = instrumentingPath;
}
processClassFile(instrumentingPath, destinationPath);
isClassFile = true;
} else {
if (destinationPath == null) {
destinationPath = instrumentingPath;
}
Utils.copyFile(instrumentingPath, destinationPath);
return;
}
if (!isClassFile) {
logger.log(Level.INFO, "Summary for ''{0}'': files total={1}, classes total={2}, instrumented classes total={3}",
new Object[]{instrumentingPath, fileCount, classCount, iClassCount});
}
}
public void processClassFileInModules(Path file, File destinationPath){
String fname = file.toAbsolutePath().toString();
try {
final String distinationStr = destinationPath.toString();
classBuf = Files.readAllBytes(file);
int classLength = classBuf.length;
byte[] outBuf = null;
try {
if (!"module-info.class".equals(file.getFileName().toString())) {
outBuf = instrument(classBuf, classLength);
}
} catch (IOException e) {
logger.log(Level.SEVERE, " Error reading data from '" + fname + "' - skipped", e);
} catch (NullPointerException e) {
logger.log(Level.SEVERE, " Error reading data from '" + fname + "' - skipped", e);
} catch (Exception e) {
logger.log(Level.SEVERE, " Error instrumenting '" + fname + "' - skipped", e);
}
if (outBuf != null) {
classLength = outBuf.length;
File outFile = new File(distinationStr + File.separator + fname);
String parentName = outFile.getParent();
if (parentName != null) {
File parent = new File(parentName);
if (!parent.exists()) {
parent.mkdirs();
}
}
// write instrumented classfile
FileOutputStream fos = new FileOutputStream(outFile);
fos.write(outBuf, 0, classLength);
try {
fos.close();
} catch (IOException e) {
logger.log(Level.SEVERE, " Error writing data to '" + outFile.getAbsolutePath() + "' - skipped", e);
}
}
}
catch(IOException e){
logger.log(Level.SEVERE, " Error processing classFile by Path '" + fname + "' - skipped", e);
}
}
private void instrumentModulesFile(File modulePath, final File destinationPath){
try {
Utils.addToClasspath(modulePath.getParentFile().getParentFile());
FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
final Path path = fs.getPath("/modules/");
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(!attrs.isDirectory() && isClassFile(file.getFileName().toString())){
OverriddenClassWriter.addClassInfo(Files.newInputStream(file));
}
return FileVisitResult.CONTINUE;
}
});
Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(!attrs.isDirectory() && isClassFile(file.getFileName().toString())){
processClassFileInModules(file, destinationPath);
}
return FileVisitResult.CONTINUE;
}
});
} catch (Exception e) {
logger.log(Level.SEVERE, "Modules instrumentaion failed", e);
}
}
/**
* <p> Treats given byte array as a class data and instruments the class.
* Any Exception thrown from this metod will be treated as error during
* instrumentation, class will be skipped. </p> <p> It's called for
* instrumenting each binary file </p>
*
* @param classData class data to be instrumented
* @param classLength length of the data
* @return bytes of instrumented class. null means class won't be changed.
*/
protected abstract byte[] instrument(byte[] classData, int classLength) throws IOException;
public abstract void finishWork();
/**
* Get classfiles from a jar file. Use to implant rt classfiles to unpacked
* binaries.
*
* @param rtJar
* @param output
* @throws IOException
*/
public void unjarRT(String rtJar, File output) throws IOException {
if (output == null) {
throw new IllegalArgumentException("Output path (jar file or classfile directory) needed to copy runtime jar file to");
}
File rt = new File(rtJar);
if (!rt.exists()) {
throw new IOException("Runtime file doesn't exist " + rt);
}
if (!rt.isFile() || !FILE_TYPE.hasExtension(rt.getName(), JAR, ZIP)) {
throw new IOException("Malformed runtime archive " + rt);
}
ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(rt)));
while (true) {
ZipEntry e0 = in.getNextEntry();
if (e0 == null) {
// are there any remaining entries?
break;
}
String ename = e0.getName();
if (ename.startsWith("META-INF")) {
continue;
}
int fileLength = (int) e0.getSize();
if (fileLength >= 0) {
// is length of the entry known?
ensureClassBufLength(fileLength, false);
// in.read(byte[],int,int) has a bug in JDK1.1.x - using in.read()...
for (int i = 0; i < fileLength; classBuf[i++] = (byte) in.read());
in.read(classBuf, 0, fileLength);
} else {
// no - read until the end of stream is encountered
int i = 0;
for (;; i++) {
int b = in.read();
if (b < 0) {
break;
}
ensureClassBufLength(i + 1, true); // make sure classBuf is big enough
classBuf[i] = (byte) b;
}
fileLength = i;
}
File outFile = new File(output.getPath() + File.separator + e0.getName());
if (!e0.isDirectory()) {
if (outFile.exists()) {
// logger.log(Level.WARNING, "Output classfile directory contains file {0} that was found in runtime jar,
// skipping without contains checking", e0.getName());
continue;
} else {
// logger.log(Level.INFO, "Adding runtime file {0} to output directory {1}",
// new Object[]{e1.getName, outDir.getName()})
String parentName = outFile.getAbsoluteFile().getParent();
if (parentName != null) {
File parent = new File(parentName);
if (!parent.exists()) {
parent.mkdirs();
}
}
FileOutputStream fos = new FileOutputStream(outFile);
fos.write(classBuf, 0, fileLength);
fos.close();
}
}
}
in.close();
}
}
| 33,426 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
MiscConstants.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/constants/MiscConstants.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.constants;
/**
* A storage for miscellaneous constants used in jcov classes.
*
* @author Konstantin Bobrovsky
*/
public interface MiscConstants {
int versionMajor = 2;
int versionMinor = 0;
// Jcov data file constants
String KWRD_FILE_VERSION = "JCOV-DATA-FILE-VERSION:";
String KWRD_CLASS = "CLASS:";
String KWRD_TIMESTAMP = "TIMESTAMP:";
String KWRD_SRCFILE = "SRCFILE:";
String KWRD_METHOD = "METHOD:";
String KWRD_FIELD = "FIELD:";
String KWRD_FILTER = "FILTER:";
String KWRD_DATA = "DATA:";
String KWRD_SUPERNAME = "SUPERNAME:";
String KWRD_SUPER_INTERFACES = "SUPER_INTERFACES:";
String KWRD_FX_ACCESS = "fxaccess:";
char COMMENT_CHAR = '#';
String SECTION_COMMENT2 = COMMENT_CHAR + "kind\tcount";
String SECTION_COMMENT3 = COMMENT_CHAR + "kind\tcount\tposition";
String SECTION_COMMENT4 = COMMENT_CHAR + "kind\tline\tposition\tcount";
String SECTION_COMMENT4_NEW = COMMENT_CHAR + "kind\tstart\tend\t\tcount";
String IDENT_LINE = KWRD_FILE_VERSION + " " + versionMajor + "." + versionMinor;
char DATA_TYPE_A = 'A';
char DATA_TYPE_B = 'B';
char DATA_TYPE_M = 'M';
char DATA_TYPE_C = 'C';
String COMPRESSED_SPECIFIER = "C";
int MAX_JCOV_LINE_LEN = 1024;
// Types of Jcov items
int CT_FIRST_KIND = 1;
int CT_METHOD = 1;
int CT_FIKT_METHOD = 2;
int CT_BLOCK = 3;
int CT_FIKT_RET = 4;
int CT_CASE = 5;
int CT_SWITCH_WO_DEF = 6;
int CT_BRANCH_TRUE = 7;
int CT_BRANCH_FALSE = 8;
int CT_LINE = 9;
int CT_LAST_KIND = 9;
String[] STR_ITEM_KIND = {
"ERROR!",
"METHOD",
"METHOD",
"BLOCK",
"BLOCK",
"BRANCH",
"BRANCH",
"true",
"false",
"LINE"
};
String[] accessModifiers = {
"public",
"private",
"protected",
"static",
"final",
"synchronized",
"volatile",
"transient",
"native",
"interface",
"abstract",
"super",
"strict",
"explicit"
};
int CRT_ENTRY_PACK_BITS = 10;
int CRT_ENTRY_POS_MASK = 0x3FF;
char JVM_PACKAGE_DELIM = '/';
String UniformSeparator = "|";
// Other Jcov constants
int JcovPortNumber = 3334; // default number of jcov port
int JcovOncePortNumber = 3335; // default number of one-time jcov port
int JcovGrabberCommandPort = 3336;
String JcovProperty = "jcov.file";
String JcovPropertyPort = "jcov.port";
String JcovAutoSave = "jcov.autosave";
String JcovServerPortProperty = "jcov.server_port";
String JcovSaveFileName = "java.jcov";
String JcovSaveFileNameXML = "result.xml";
String JcovTemplateFileNameXML = "template.xml";
String JcovDataStreamEndTag = "# END OF JCOV DATA";
String JcovDataStreamStartTag = "# START OF JCOV DATA";
String urlDelim = ",";
public static final int GRABBER_KILL_COMMAND = 1;
public static final int GRABBER_FORCE_KILL_COMMAND = 2;
public static final int GRABBER_SAVE_COMMAND = 3;
public static final int GRABBER_STATUS_COMMAND = 4;
public static final int GRABBER_WAIT_COMMAND = 5;
}
| 4,428 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
InstrConstants.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/constants/InstrConstants.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.constants;
/*
* @author Dmitry Fazunenko
*/
public interface InstrConstants {
String sccsVersion = "%I% $LastChangedDate: 2008-08-08 19:46:37 +0400 (Fri, 08 Aug 2008) $";
// types of jcov instrumentation
int instrByMethod = 0x1;
int instrByBlock = 0x2;
int instrByBranch = 0x4;
int instrByAll = 0x7;
// types of additional instrumentation
int addSaveBefore = 1;
int addSaveAfter = 2;
int addSaveBegin = 3;
int addSaveAtEnd = 4;
// flags for others jcov features
int synchGathFlag = 0x1;
int autoCollectFlag = 0x2;
int commonTimeStampFlag = 0x4;
int noStartSatellite = 0x8;
// index in class description array
int indexClassName = 0;
int indexTimestamp = 1;
int indexScrFile = 2;
int indexModifiers = 3;
//
int commonTimeStamp = 1;
//
int codeGathering = 0;
int codeReRegistration = 1;
int codeNotGathering = 2;
//
int scaleAutoGathering = 0x1;
int scaleCollectSattelite = 0x2;
String INSTR_FILE_SUFF = "i";
}
| 2,241 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
VMConstants.java | /FileExtraction/Java_unseen/openjdk_jcov/src/classes/com/sun/tdk/jcov/constants/VMConstants.java | /*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tdk.jcov.constants;
/*
* @author Dmitry Fazunenko
*/
public interface VMConstants {
/* Signature Characters */
char SIGC_VOID = 'V';
String SIG_VOID = "V";
char SIGC_BOOLEAN = 'Z';
String SIG_BOOLEAN = "Z";
char SIGC_BYTE = 'B';
String SIG_BYTE = "B";
char SIGC_CHAR = 'C';
String SIG_CHAR = "C";
char SIGC_SHORT = 'S';
String SIG_SHORT = "S";
char SIGC_INT = 'I';
String SIG_INT = "I";
char SIGC_LONG = 'J';
String SIG_LONG = "J";
char SIGC_FLOAT = 'F';
String SIG_FLOAT = "F";
char SIGC_DOUBLE = 'D';
String SIG_DOUBLE = "D";
char SIGC_ARRAY = '[';
String SIG_ARRAY = "[";
char SIGC_CLASS = 'L';
String SIG_CLASS = "L";
char SIGC_METHOD = '(';
String SIG_METHOD = "(";
char SIGC_ENDCLASS = ';';
String SIG_ENDCLASS = ";";
char SIGC_ENDMETHOD = ')';
String SIG_ENDMETHOD = ")";
char SIGC_PACKAGE = '/';
String SIG_PACKAGE = "/";
/* Class File Constants */
int JAVA_MAGIC = 0xcafebabe;
int JAVA_VERSION = 45;
int JAVA_MINOR_VERSION = 3;
/* Constant table */
int CONSTANT_UTF8 = 1;
int CONSTANT_UNICODE = 2;
int CONSTANT_INTEGER = 3;
int CONSTANT_FLOAT = 4;
int CONSTANT_LONG = 5;
int CONSTANT_DOUBLE = 6;
int CONSTANT_CLASS = 7;
int CONSTANT_STRING = 8;
int CONSTANT_FIELD = 9;
int CONSTANT_METHOD = 10;
int CONSTANT_INTERFACEMETHOD = 11;
int CONSTANT_NAMEANDTYPE = 12;
/* Access and modifier flags */
int ACC_PUBLIC = 0x00000001;
int ACC_PRIVATE = 0x00000002;
int ACC_PROTECTED = 0x00000004;
int ACC_STATIC = 0x00000008;
int ACC_FINAL = 0x00000010;
int ACC_SYNCHRONIZED = 0x00000020;
int ACC_VOLATILE = 0x00000040;
int ACC_TRANSIENT = 0x00000080;
int ACC_NATIVE = 0x00000100;
int ACC_INTERFACE = 0x00000200;
int ACC_ABSTRACT = 0x00000400;
int ACC_SUPER = 0x00000020;
int ACC_STRICT = 0x00000800;
int ACC_EXPLICIT = 0x00001000;
/* Type codes */
int T_CLASS = 0x00000002;
int T_BOOLEAN = 0x00000004;
int T_CHAR = 0x00000005;
int T_FLOAT = 0x00000006;
int T_DOUBLE = 0x00000007;
int T_BYTE = 0x00000008;
int T_SHORT = 0x00000009;
int T_INT = 0x0000000a;
int T_LONG = 0x0000000b;
/* */
int[] ACCESS_MOD_ARRAY = {
ACC_PUBLIC,
ACC_PRIVATE,
ACC_PROTECTED,
ACC_STATIC,
ACC_FINAL,
0 /*ACC_SYNCHRONIZED*/,
0 /*ACC_VOLATILE*/,
0 /*ACC_TRANSIENT*/,
ACC_NATIVE,
ACC_INTERFACE,
ACC_ABSTRACT,
0 /*ACC_SUPER*/,
0 /*ACC_STRICT*/,
0 /*ACC_EXPLICIT*/};
String[] AccessModifierNames = {
"public",
"private",
"protected",
"static",
"final",
"",
"",
"",
"native",
"interface",
"abstract",
"",
"",
""
};
/* Opcodes */
int opc_try = -3;
int opc_dead = -2;
int opc_label = -1;
int opc_nop = 0;
int opc_aconst_null = 1;
int opc_iconst_m1 = 2;
int opc_iconst_0 = 3;
int opc_iconst_1 = 4;
int opc_iconst_2 = 5;
int opc_iconst_3 = 6;
int opc_iconst_4 = 7;
int opc_iconst_5 = 8;
int opc_lconst_0 = 9;
int opc_lconst_1 = 10;
int opc_fconst_0 = 11;
int opc_fconst_1 = 12;
int opc_fconst_2 = 13;
int opc_dconst_0 = 14;
int opc_dconst_1 = 15;
int opc_bipush = 16;
int opc_sipush = 17;
int opc_ldc = 18;
int opc_ldc_w = 19;
int opc_ldc2_w = 20;
int opc_iload = 21;
int opc_lload = 22;
int opc_fload = 23;
int opc_dload = 24;
int opc_aload = 25;
int opc_iload_0 = 26;
int opc_iload_1 = 27;
int opc_iload_2 = 28;
int opc_iload_3 = 29;
int opc_lload_0 = 30;
int opc_lload_1 = 31;
int opc_lload_2 = 32;
int opc_lload_3 = 33;
int opc_fload_0 = 34;
int opc_fload_1 = 35;
int opc_fload_2 = 36;
int opc_fload_3 = 37;
int opc_dload_0 = 38;
int opc_dload_1 = 39;
int opc_dload_2 = 40;
int opc_dload_3 = 41;
int opc_aload_0 = 42;
int opc_aload_1 = 43;
int opc_aload_2 = 44;
int opc_aload_3 = 45;
int opc_iaload = 46;
int opc_laload = 47;
int opc_faload = 48;
int opc_daload = 49;
int opc_aaload = 50;
int opc_baload = 51;
int opc_caload = 52;
int opc_saload = 53;
int opc_istore = 54;
int opc_lstore = 55;
int opc_fstore = 56;
int opc_dstore = 57;
int opc_astore = 58;
int opc_istore_0 = 59;
int opc_istore_1 = 60;
int opc_istore_2 = 61;
int opc_istore_3 = 62;
int opc_lstore_0 = 63;
int opc_lstore_1 = 64;
int opc_lstore_2 = 65;
int opc_lstore_3 = 66;
int opc_fstore_0 = 67;
int opc_fstore_1 = 68;
int opc_fstore_2 = 69;
int opc_fstore_3 = 70;
int opc_dstore_0 = 71;
int opc_dstore_1 = 72;
int opc_dstore_2 = 73;
int opc_dstore_3 = 74;
int opc_astore_0 = 75;
int opc_astore_1 = 76;
int opc_astore_2 = 77;
int opc_astore_3 = 78;
int opc_iastore = 79;
int opc_lastore = 80;
int opc_fastore = 81;
int opc_dastore = 82;
int opc_aastore = 83;
int opc_bastore = 84;
int opc_castore = 85;
int opc_sastore = 86;
int opc_pop = 87;
int opc_pop2 = 88;
int opc_dup = 89;
int opc_dup_x1 = 90;
int opc_dup_x2 = 91;
int opc_dup2 = 92;
int opc_dup2_x1 = 93;
int opc_dup2_x2 = 94;
int opc_swap = 95;
int opc_iadd = 96;
int opc_ladd = 97;
int opc_fadd = 98;
int opc_dadd = 99;
int opc_isub = 100;
int opc_lsub = 101;
int opc_fsub = 102;
int opc_dsub = 103;
int opc_imul = 104;
int opc_lmul = 105;
int opc_fmul = 106;
int opc_dmul = 107;
int opc_idiv = 108;
int opc_ldiv = 109;
int opc_fdiv = 110;
int opc_ddiv = 111;
int opc_irem = 112;
int opc_lrem = 113;
int opc_frem = 114;
int opc_drem = 115;
int opc_ineg = 116;
int opc_lneg = 117;
int opc_fneg = 118;
int opc_dneg = 119;
int opc_ishl = 120;
int opc_lshl = 121;
int opc_ishr = 122;
int opc_lshr = 123;
int opc_iushr = 124;
int opc_lushr = 125;
int opc_iand = 126;
int opc_land = 127;
int opc_ior = 128;
int opc_lor = 129;
int opc_ixor = 130;
int opc_lxor = 131;
int opc_iinc = 132;
int opc_i2l = 133;
int opc_i2f = 134;
int opc_i2d = 135;
int opc_l2i = 136;
int opc_l2f = 137;
int opc_l2d = 138;
int opc_f2i = 139;
int opc_f2l = 140;
int opc_f2d = 141;
int opc_d2i = 142;
int opc_d2l = 143;
int opc_d2f = 144;
int opc_i2b = 145;
int opc_i2c = 146;
int opc_i2s = 147;
int opc_lcmp = 148;
int opc_fcmpl = 149;
int opc_fcmpg = 150;
int opc_dcmpl = 151;
int opc_dcmpg = 152;
int opc_ifeq = 153;
int opc_ifne = 154;
int opc_iflt = 155;
int opc_ifge = 156;
int opc_ifgt = 157;
int opc_ifle = 158;
int opc_if_icmpeq = 159;
int opc_if_icmpne = 160;
int opc_if_icmplt = 161;
int opc_if_icmpge = 162;
int opc_if_icmpgt = 163;
int opc_if_icmple = 164;
int opc_if_acmpeq = 165;
int opc_if_acmpne = 166;
int opc_goto = 167;
int opc_jsr = 168;
int opc_ret = 169;
int opc_tableswitch = 170;
int opc_lookupswitch = 171;
int opc_ireturn = 172;
int opc_lreturn = 173;
int opc_freturn = 174;
int opc_dreturn = 175;
int opc_areturn = 176;
int opc_return = 177;
int opc_getstatic = 178;
int opc_putstatic = 179;
int opc_getfield = 180;
int opc_putfield = 181;
int opc_invokevirtual = 182;
int opc_invokespecial = 183;
int opc_invokestatic = 184;
int opc_invokeinterface = 185;
int opc_xxxunusedxxx = 186;
int opc_new = 187;
int opc_newarray = 188;
int opc_anewarray = 189;
int opc_arraylength = 190;
int opc_athrow = 191;
int opc_checkcast = 192;
int opc_instanceof = 193;
int opc_monitorenter = 194;
int opc_monitorexit = 195;
int opc_wide = 196;
int opc_multianewarray = 197;
int opc_ifnull = 198;
int opc_ifnonnull = 199;
int opc_goto_w = 200;
int opc_jsr_w = 201;
int opc_breakpoint = 202;
/* Opcode Names */
String opcNames[] = {
"nop",
"aconst_null",
"iconst_m1",
"iconst_0",
"iconst_1",
"iconst_2",
"iconst_3",
"iconst_4",
"iconst_5",
"lconst_0",
"lconst_1",
"fconst_0",
"fconst_1",
"fconst_2",
"dconst_0",
"dconst_1",
"bipush",
"sipush",
"ldc",
"ldc_w",
"ldc2_w",
"iload",
"lload",
"fload",
"dload",
"aload",
"iload_0",
"iload_1",
"iload_2",
"iload_3",
"lload_0",
"lload_1",
"lload_2",
"lload_3",
"fload_0",
"fload_1",
"fload_2",
"fload_3",
"dload_0",
"dload_1",
"dload_2",
"dload_3",
"aload_0",
"aload_1",
"aload_2",
"aload_3",
"iaload",
"laload",
"faload",
"daload",
"aaload",
"baload",
"caload",
"saload",
"istore",
"lstore",
"fstore",
"dstore",
"astore",
"istore_0",
"istore_1",
"istore_2",
"istore_3",
"lstore_0",
"lstore_1",
"lstore_2",
"lstore_3",
"fstore_0",
"fstore_1",
"fstore_2",
"fstore_3",
"dstore_0",
"dstore_1",
"dstore_2",
"dstore_3",
"astore_0",
"astore_1",
"astore_2",
"astore_3",
"iastore",
"lastore",
"fastore",
"dastore",
"aastore",
"bastore",
"castore",
"sastore",
"pop",
"pop2",
"dup",
"dup_x1",
"dup_x2",
"dup2",
"dup2_x1",
"dup2_x2",
"swap",
"iadd",
"ladd",
"fadd",
"dadd",
"isub",
"lsub",
"fsub",
"dsub",
"imul",
"lmul",
"fmul",
"dmul",
"idiv",
"ldiv",
"fdiv",
"ddiv",
"irem",
"lrem",
"frem",
"drem",
"ineg",
"lneg",
"fneg",
"dneg",
"ishl",
"lshl",
"ishr",
"lshr",
"iushr",
"lushr",
"iand",
"land",
"ior",
"lor",
"ixor",
"lxor",
"iinc",
"i2l",
"i2f",
"i2d",
"l2i",
"l2f",
"l2d",
"f2i",
"f2l",
"f2d",
"d2i",
"d2l",
"d2f",
"i2b",
"i2c",
"i2s",
"lcmp",
"fcmpl",
"fcmpg",
"dcmpl",
"dcmpg",
"ifeq",
"ifne",
"iflt",
"ifge",
"ifgt",
"ifle",
"if_icmpeq",
"if_icmpne",
"if_icmplt",
"if_icmpge",
"if_icmpgt",
"if_icmple",
"if_acmpeq",
"if_acmpne",
"goto",
"jsr",
"ret",
"tableswitch",
"lookupswitch",
"ireturn",
"lreturn",
"freturn",
"dreturn",
"areturn",
"return",
"getstatic",
"putstatic",
"getfield",
"putfield",
"invokevirtual",
"invokespecial",
"invokestatic",
"invokeinterface",
"xxxunusedxxx",
"new",
"newarray",
"anewarray",
"arraylength",
"athrow",
"checkcast",
"instanceof",
"monitorenter",
"monitorexit",
"wide",
"multianewarray",
"ifnull",
"ifnonnull",
"goto_w",
"jsr_w",
"breakpoint"
};
/* Opcode Lengths */
int opcLengths[] = {
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
3,
2,
3,
3,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
2,
2,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
3,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
3,
2,
99,
99,
1,
1,
1,
1,
1,
1,
3,
3,
3,
3,
3,
3,
3,
5,
0,
3,
2,
3,
1,
1,
3,
3,
1,
1,
0,
4,
3,
3,
5,
5,
1
};
}
| 15,521 | Java | .java | openjdk/jcov | 16 | 12 | 0 | 2019-05-15T06:46:03Z | 2024-04-16T17:20:11Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.