repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
ceph-main/examples/rgw/java/ceph-s3-upload/src/main/java/org/example/cephs3upload/App.java
package org.example.cephs3upload; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import java.io.File; import java.nio.file.Paths; public class App { public static void main( String[] args ) { final String USAGE = "\n" + "To run this example, supply the name of an S3 bucket and a file to\n" + "upload to it.\n" + "\n" + "Ex: java -jar target/ceph-s3-upload-1.0-SNAPSHOT-jar-with-dependencies.jar <bucketname> <filename>\n"; if (args.length < 2) { System.out.println(USAGE); System.exit(1); } String bucket_name = args[0]; String file_path = args[1]; String key_name = Paths.get(file_path).getFileName().toString(); System.out.format("Uploading %s to S3 bucket %s...\n", file_path, bucket_name); // Put in the CEPH RGW access and secret keys here in that order "access key" "secret key" // Must also be specified here BasicAWSCredentials credentials = new BasicAWSCredentials("0555b35654ad1656d804","h7GhxuBLTrlhVUyxSPUKUV8r/2EI4ngqJxD7iBdBYLhwluN30JaT3Q=="); // Note That the AWSClient builder takes in the endpoint and the region // This has to be specified in this file final AmazonS3 s3 = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://127.0.0.1:8000", "default")) .build(); try { s3.putObject(bucket_name, key_name, new File(file_path)); } catch (AmazonS3Exception e) { System.err.println(e.getMessage()); // raises more explicit error message than e.getErrorMessage() e.g when Bucket is not available System.exit(1); } System.out.println("Object upload successful!"); } }
2,294
43.134615
149
java
null
ceph-main/examples/rgw/java/ceph-s3-upload/src/test/java/org/example/cephs3upload/AppTest.java
package org.example.cephs3upload; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() { assertTrue( true ); } }
652
15.74359
46
java
null
ceph-main/src/java/java/com/ceph/crush/Bucket.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.crush; public class Bucket { private String type; private String name; public Bucket(String type, String name) { this.type = type; this.name = name; } public String getType() { return type; } public String getName() { return name; } public String toString() { return "bucket[" + type + "," + name + "]"; } }
1,449
32.72093
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephAlreadyMountedException.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.IOException; /** * Ceph is already mounted. */ public class CephAlreadyMountedException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephAlreadyMountedException. */ public CephAlreadyMountedException() { super(); } /** * Construct CephAlreadyMountedException with message. */ public CephAlreadyMountedException(String s) { super(s); } }
1,535
33.133333
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephFileAlreadyExistsException.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.IOException; /** * Ceph file/directory already exists. */ public class CephFileAlreadyExistsException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephFileAlreadyExistsException. */ public CephFileAlreadyExistsException() { super(); } /** * Construct CephFileAlreadyExistsException with message. */ public CephFileAlreadyExistsException(String s) { super(s); } }
1,561
33.711111
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephFileExtent.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.util.Arrays; /** * Holds information about a file extent in CephFS. */ public class CephFileExtent { private long offset; private long length; private int[] osds; CephFileExtent(long offset, long length, int[] osds) { this.offset = offset; this.length = length; this.osds = osds; } /** * Get starting offset of extent. */ public long getOffset() { return offset; } /** * Get length of extent. */ public long getLength() { return length; } /** * Get list of OSDs with this extent. */ public int[] getOSDs() { return osds; } /** * Pretty print. */ public String toString() { return "extent[" + offset + "," + length + "," + Arrays.toString(osds) + "]"; } }
1,868
26.895522
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephMount.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.IOException; import java.io.FileNotFoundException; import java.net.InetAddress; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.lang.String; import com.ceph.crush.Bucket; public class CephMount { /* * Set via JNI callback in native_ceph_create * * Do not touch! */ private long instance_ptr; /* * Flags for open(). * * Must be synchronized with JNI if changed. */ public static final int O_RDONLY = 1; public static final int O_RDWR = 2; public static final int O_APPEND = 4; public static final int O_CREAT = 8; public static final int O_TRUNC = 16; public static final int O_EXCL = 32; public static final int O_WRONLY = 64; public static final int O_DIRECTORY = 128; /* * Whence flags for seek(). * * Must be synchronized with JNI if changed. */ public static final int SEEK_SET = 1; public static final int SEEK_CUR = 2; public static final int SEEK_END = 3; /* * Attribute flags for setattr(). * * Must be synchronized with JNI if changed. */ public static final int SETATTR_MODE = 1; public static final int SETATTR_UID = 2; public static final int SETATTR_GID = 4; public static final int SETATTR_MTIME = 8; public static final int SETATTR_ATIME = 16; /* * Flags for setxattr(); * * Must be synchronized with JNI if changed. */ public static final int XATTR_CREATE = 1; public static final int XATTR_REPLACE = 2; public static final int XATTR_NONE = 3; /* * Flags for flock(); * * Must be synchronized with JNI if changed. */ public static final int LOCK_SH = 1; public static final int LOCK_EX = 2; public static final int LOCK_NB = 4; public static final int LOCK_UN = 8; /* * This is run by the class loader and will report early any problems * finding or linking in the shared JNI library. */ static { loadLibrary(); } static synchronized void loadLibrary() { CephNativeLoader.getInstance().loadLibrary(); } /* * Package-private: called from CephNativeLoader */ static native void native_initialize(); /* * RW lock used for fine grained synchronization to native */ private final ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock(); private final Lock rlock = rwlock.readLock(); private final Lock wlock = rwlock.writeLock(); /* * Controls clean-up synchronization between the constructor and finalize(). * If native_ceph_create fails, then we want a call to finalize() to not * attempt to clean-up native context, because there is none. */ private boolean initialized = false; /* * Try to clean-up. First, unmount() will catch users who forget to do the * unmount manually. Second, release() will destroy the entire context. It * is safe to call release after a failure in unmount. */ protected void finalize() throws Throwable { if (initialized) { try { unmount(); } catch (Exception e) {} try { native_ceph_release(instance_ptr); } catch (Exception e) {} } super.finalize(); } /** * Create a new CephMount with specific client id. * * @param id client id. */ public CephMount(String id) { native_ceph_create(this, id); initialized = true; } private static native int native_ceph_create(CephMount mount, String id); /** * Create a new CephMount with default client id. */ public CephMount() { this(null); } /** * Activate the mount with a given root path. * * @param root The path to use as the root (pass null for "/"). */ public void mount(String root) { wlock.lock(); try { native_ceph_mount(instance_ptr, root); } finally { wlock.unlock(); } } private static native int native_ceph_mount(long mountp, String root); /** * Deactivate the mount. * * The mount can be reactivated using mount(). Configuration parameters * previously set are not reset. */ public void unmount() { wlock.lock(); try { native_ceph_unmount(instance_ptr); } finally { wlock.unlock(); } } private static native int native_ceph_unmount(long mountp); /* * Private access to low-level ceph_release. */ private static native int native_ceph_release(long mountp); /** * Load configuration from a file. * * @param path The path to the configuration file. */ public void conf_read_file(String path) throws FileNotFoundException { rlock.lock(); try { native_ceph_conf_read_file(instance_ptr, path); } finally { rlock.unlock(); } } private static native int native_ceph_conf_read_file(long mountp, String path); /** * Set the value of a configuration option. * * @param option The configuration option to modify. * @param value The new value of the option. */ public void conf_set(String option, String value) { rlock.lock(); try { native_ceph_conf_set(instance_ptr, option, value); } finally { rlock.unlock(); } } private static native int native_ceph_conf_set(long mountp, String option, String value); /** * Get the value of a configuration option. * * @param option The name of the configuration option. * @return The value of the option or null if option not found */ public String conf_get(String option) { rlock.lock(); try { return native_ceph_conf_get(instance_ptr, option); } finally { rlock.unlock(); } } private static native String native_ceph_conf_get(long mountp, String option); /** * Get file system status. * * @param path Path to file in file system. * @param statvfs CephStatVFS structure to hold status. */ public void statfs(String path, CephStatVFS statvfs) throws FileNotFoundException { rlock.lock(); try { native_ceph_statfs(instance_ptr, path, statvfs); } finally { rlock.unlock(); } } private static native int native_ceph_statfs(long mountp, String path, CephStatVFS statvfs); /** * Get the current working directory. * * @return The current working directory in Ceph. */ public String getcwd() { rlock.lock(); try { return native_ceph_getcwd(instance_ptr); } finally { rlock.unlock(); } } private static native String native_ceph_getcwd(long mountp); /** * Set the current working directory. * * @param path The directory set as the cwd. */ public void chdir(String path) throws FileNotFoundException { rlock.lock(); try { native_ceph_chdir(instance_ptr, path); } finally { rlock.unlock(); } } private static native int native_ceph_chdir(long mountp, String cwd); /** * List the contents of a directory. * * @param dir The directory. * @return List of files and directories excluding "." and "..". */ public String[] listdir(String dir) throws FileNotFoundException { rlock.lock(); try { return native_ceph_listdir(instance_ptr, dir); } finally { rlock.unlock(); } } private static native String[] native_ceph_listdir(long mountp, String path); /** * Create a hard link to an existing file. * * @param oldpath The target path of the link. * @param newpath The name of the link. */ public void link(String oldpath, String newpath) throws FileNotFoundException { rlock.lock(); try { native_ceph_link(instance_ptr, oldpath, newpath); } finally { rlock.unlock(); } } private static native int native_ceph_link(long mountp, String existing, String newname); /** * Unlink/delete a name from the file system. * * @param path The name to unlink/delete. */ public void unlink(String path) throws FileNotFoundException { rlock.lock(); try { native_ceph_unlink(instance_ptr, path); } finally { rlock.unlock(); } } private static native int native_ceph_unlink(long mountp, String path); /** * Rename a file or directory. * * @param from The current path. * @param to The new path. */ public void rename(String from, String to) throws FileNotFoundException { rlock.lock(); try { native_ceph_rename(instance_ptr, from, to); } finally { rlock.unlock(); } } private static native int native_ceph_rename(long mountp, String from, String to); /** * Create a directory. * * @param path The directory to create. * @param mode The mode of the new directory. */ public void mkdir(String path, int mode) { rlock.lock(); try { native_ceph_mkdir(instance_ptr, path, mode); } finally { rlock.unlock(); } } private static native int native_ceph_mkdir(long mountp, String path, int mode); /** * Create a directory and all parents. * * @param path The directory to create. * @param mode The mode of the new directory. */ public void mkdirs(String path, int mode) throws IOException { rlock.lock(); try { native_ceph_mkdirs(instance_ptr, path, mode); } finally { rlock.unlock(); } } private static native int native_ceph_mkdirs(long mountp, String path, int mode); /** * Delete a directory. * * @param path The directory to delete. */ public void rmdir(String path) throws FileNotFoundException { rlock.lock(); try { native_ceph_rmdir(instance_ptr, path); } finally { rlock.unlock(); } } private static native int native_ceph_rmdir(long mountp, String path); /** * Read the value of a symbolic link. */ public String readlink(String path) throws FileNotFoundException { rlock.lock(); try { return native_ceph_readlink(instance_ptr, path); } finally { rlock.unlock(); } } private static native String native_ceph_readlink(long mountp, String path); /** * Create a symbolic link. * * @param oldpath Target of the symbolic link. * @param newpath Name of the link. */ public void symlink(String oldpath, String newpath) { rlock.lock(); try { native_ceph_symlink(instance_ptr, oldpath, newpath); } finally { rlock.unlock(); } } private static native int native_ceph_symlink(long mountp, String existing, String newname); /** * Get file status. * * @param path Path of file to stat. * @param stat CephStat structure to hold file status. */ public void stat(String path, CephStat stat) throws FileNotFoundException, CephNotDirectoryException { rlock.lock(); try { native_ceph_stat(instance_ptr, path, stat); } finally { rlock.unlock(); } } private static native int native_ceph_stat(long mountp, String path, CephStat stat); /** * Get file status, without following symlinks. * * @param path Path of file to stat. * @param stat CephStat structure to hold file status. */ public void lstat(String path, CephStat stat) throws FileNotFoundException, CephNotDirectoryException { rlock.lock(); try { native_ceph_lstat(instance_ptr, path, stat); } finally { rlock.unlock(); } } private static native int native_ceph_lstat(long mountp, String path, CephStat stat); /** * Set file attributes. * * @param path Path to file. * @param stat CephStat structure holding attributes. * @param mask Mask specifying which attributes to set. */ public void setattr(String path, CephStat stat, int mask) throws FileNotFoundException { rlock.lock(); try { native_ceph_setattr(instance_ptr, path, stat, mask); } finally { rlock.unlock(); } } private static native int native_ceph_setattr(long mountp, String relpath, CephStat stat, int mask); /** * Change file mode. * * @param path Path to file. * @param mode New mode bits. */ public void chmod(String path, int mode) throws FileNotFoundException { rlock.lock(); try { native_ceph_chmod(instance_ptr, path, mode); } finally { rlock.unlock(); } } private static native int native_ceph_chmod(long mountp, String path, int mode); /** * Change file mode of an open file. * * @param fd The open file descriptor to change the mode bits on. * @param mode New mode bits. */ public void fchmod(int fd, int mode) { rlock.lock(); try { native_ceph_fchmod(instance_ptr, fd, mode); } finally { rlock.unlock(); } } private static native int native_ceph_fchmod(long mountp, int fd, int mode); /** * Truncate a file to a specified length. * * @param path Path of the file. * @param size New file length. */ public void truncate(String path, long size) throws FileNotFoundException { rlock.lock(); try { native_ceph_truncate(instance_ptr, path, size); } finally { rlock.unlock(); } } private static native int native_ceph_truncate(long mountp, String path, long size); /** * Open a file. * * @param path Path of file to open or create. * @param flags Open flags. * @param mode Permission mode. * @return File descriptor. */ public int open(String path, int flags, int mode) throws FileNotFoundException { rlock.lock(); try { return native_ceph_open(instance_ptr, path, flags, mode); } finally { rlock.unlock(); } } private static native int native_ceph_open(long mountp, String path, int flags, int mode); /** * Open a file with a specific file layout. * * @param path Path of file to open or create. * @param flags Open flags. * @param mode Permission mode. * @param stripe_unit File layout stripe unit size. * @param stripe_count File layout stripe count. * @param object_size Size of each object. * @param data_pool The target data pool. * @return File descriptor. */ public int open(String path, int flags, int mode, int stripe_unit, int stripe_count, int object_size, String data_pool) throws FileNotFoundException { rlock.lock(); try { return native_ceph_open_layout(instance_ptr, path, flags, mode, stripe_unit, stripe_count, object_size, data_pool); } finally { rlock.unlock(); } } private static native int native_ceph_open_layout(long mountp, String path, int flags, int mode, int stripe_unit, int stripe_count, int object_size, String data_pool); /** * Close an open file. * * @param fd The file descriptor. */ public void close(int fd) { rlock.lock(); try { native_ceph_close(instance_ptr, fd); } finally { rlock.unlock(); } } private static native int native_ceph_close(long mountp, int fd); /** * Seek to a position in a file. * * @param fd File descriptor. * @param offset New offset. * @param whence Whence value. * @return The new offset. */ public long lseek(int fd, long offset, int whence) { rlock.lock(); try { return native_ceph_lseek(instance_ptr, fd, offset, whence); } finally { rlock.unlock(); } } private static native long native_ceph_lseek(long mountp, int fd, long offset, int whence); /** * Read from a file. * * @param fd The file descriptor. * @param buf Buffer to for data read. * @param size Amount of data to read into the buffer. * @param offset Offset to read from (-1 for current position). * @return The number of bytes read. */ public long read(int fd, byte[] buf, long size, long offset) { rlock.lock(); try { return native_ceph_read(instance_ptr, fd, buf, size, offset); } finally { rlock.unlock(); } } private static native long native_ceph_read(long mountp, int fd, byte[] buf, long size, long offset); /** * Write to a file at a specific offset. * * @param fd The file descriptor. * @param buf Buffer to write. * @param size Amount of data to write. * @param offset Offset to write from (-1 for current position). * @return The number of bytes written. */ public long write(int fd, byte[] buf, long size, long offset) { rlock.lock(); try { return native_ceph_write(instance_ptr, fd, buf, size, offset); } finally { rlock.unlock(); } } private static native long native_ceph_write(long mountp, int fd, byte[] buf, long size, long offset); /** * Truncate a file. * * @param fd File descriptor of the file to truncate. * @param size New file size. */ public void ftruncate(int fd, long size) { rlock.lock(); try { native_ceph_ftruncate(instance_ptr, fd, size); } finally { rlock.unlock(); } } private static native int native_ceph_ftruncate(long mountp, int fd, long size); /** * Synchronize a file with the file system. * * @param fd File descriptor to synchronize. * @param dataonly Synchronize only data. */ public void fsync(int fd, boolean dataonly) { rlock.lock(); try { native_ceph_fsync(instance_ptr, fd, dataonly); } finally { rlock.unlock(); } } private static native int native_ceph_fsync(long mountp, int fd, boolean dataonly); /** * Apply or remove an advisory lock. * * @param fd File descriptor to lock or unlock. * @param operation the advisory lock operation to be performed on the file * descriptor among LOCK_SH (shared lock), LOCK_EX (exclusive lock), * or LOCK_UN (remove lock). The LOCK_NB value can be ORed to perform a * non-blocking operation. * @param owner the user-supplied owner identifier (an arbitrary integer) */ public void flock(int fd, int operation, long owner) throws IOException { rlock.lock(); try { native_ceph_flock(instance_ptr, fd, operation, owner); } finally { rlock.unlock(); } } private static native int native_ceph_flock(long mountp, int fd, int operation, long owner); /** * Get file status. * * @param fd The file descriptor. * @param stat The object in which to store the status. */ public void fstat(int fd, CephStat stat) { rlock.lock(); try { native_ceph_fstat(instance_ptr, fd, stat); } finally { rlock.unlock(); } } private static native int native_ceph_fstat(long mountp, int fd, CephStat stat); /** * Synchronize the client with the file system. */ public void sync_fs() { rlock.lock(); try { native_ceph_sync_fs(instance_ptr); } finally { rlock.unlock(); } } private static native int native_ceph_sync_fs(long mountp); /** * Get an extended attribute value. * * If the buffer is large enough to hold the entire attribute value, or * buf is null, the size of the value is returned. * * @param path File path. * @param name Name of the attribute. * @param buf Buffer to store attribute value. * @return The length of the attribute value. See description for more * details. */ public long getxattr(String path, String name, byte[] buf) throws FileNotFoundException { rlock.lock(); try { return native_ceph_getxattr(instance_ptr, path, name, buf); } finally { rlock.unlock(); } } private static native long native_ceph_getxattr(long mountp, String path, String name, byte[] buf); /** * Get an extended attribute value of a symbolic link. * * If the buffer is large enough to hold the entire attribute value, or * buf is null, the size of the value is returned. * * @param path File path. * @param name Name of attribute. * @param buf Buffer to store attribute value. * @return The length of the attribute value. See description for more * details. */ public long lgetxattr(String path, String name, byte[] buf) throws FileNotFoundException { rlock.lock(); try { return native_ceph_lgetxattr(instance_ptr, path, name, buf); } finally { rlock.unlock(); } } private static native long native_ceph_lgetxattr(long mountp, String path, String name, byte[] buf); /** * List extended attributes. * * @param path File path. * @return List of attribute names. */ public String[] listxattr(String path) throws FileNotFoundException { rlock.lock(); try { return native_ceph_listxattr(instance_ptr, path); } finally { rlock.unlock(); } } private static native String[] native_ceph_listxattr(long mountp, String path); /** * List extended attributes of a symbolic link. * * @param path File path. * @return List of attribute names. */ public String[] llistxattr(String path) throws FileNotFoundException { rlock.lock(); try { return native_ceph_llistxattr(instance_ptr, path); } finally { rlock.unlock(); } } private static native String[] native_ceph_llistxattr(long mountp, String path); /** * Remove an extended attribute. * * @param path File path. * @param name Name of attribute. */ public void removexattr(String path, String name) throws FileNotFoundException { rlock.lock(); try { native_ceph_removexattr(instance_ptr, path, name); } finally { rlock.unlock(); } } private static native int native_ceph_removexattr(long mountp, String path, String name); /** * Remove an extended attribute from a symbolic link. * * @param path File path. * @param name Name of attribute. */ public void lremovexattr(String path, String name) throws FileNotFoundException { rlock.lock(); try { native_ceph_lremovexattr(instance_ptr, path, name); } finally { rlock.unlock(); } } private static native int native_ceph_lremovexattr(long mountp, String path, String name); /** * Set the value of an extended attribute. * * @param path The file path. * @param name The attribute name. * @param buf The attribute value. * @param size The size of the attribute value. * @param flags Flag controlling behavior (XATTR_CREATE/REPLACE/NONE). */ public void setxattr(String path, String name, byte[] buf, long size, int flags) throws FileNotFoundException { rlock.lock(); try { native_ceph_setxattr(instance_ptr, path, name, buf, size, flags); } finally { rlock.unlock(); } } private static native int native_ceph_setxattr(long mountp, String path, String name, byte[] buf, long size, int flags); /** * Set the value of an extended attribute on a symbolic link. * * @param path The file path. * @param name The attribute name. * @param buf The attribute value. * @param size The size of the attribute value. * @param flags Flag controlling behavior (XATTR_CREATE/REPLACE/NONE). */ public void lsetxattr(String path, String name, byte[] buf, long size, int flags) throws FileNotFoundException { rlock.lock(); try { native_ceph_lsetxattr(instance_ptr, path, name, buf, size, flags); } finally { rlock.unlock(); } } private static native int native_ceph_lsetxattr(long mountp, String path, String name, byte[] buf, long size, int flags); /** * Get the stripe unit of a file. * * @param fd The file descriptor. * @return The stripe unit. */ public int get_file_stripe_unit(int fd) { rlock.lock(); try { return native_ceph_get_file_stripe_unit(instance_ptr, fd); } finally { rlock.unlock(); } } private static native int native_ceph_get_file_stripe_unit(long mountp, int fd); /** * Get the name of the pool a file is stored in. * * @param fd An open file descriptor. * @return The pool name. */ public String get_file_pool_name(int fd) { rlock.lock(); try { return native_ceph_get_file_pool_name(instance_ptr, fd); } finally { rlock.unlock(); } } private static native String native_ceph_get_file_pool_name(long mountp, int fd); /** * Get the default data pool of cephfs. * * @return The pool name. */ public String get_default_data_pool_name() { rlock.lock(); try { return native_ceph_get_default_data_pool_name(instance_ptr); } finally { rlock.unlock(); } } private static native String native_ceph_get_default_data_pool_name(long mountp); /** * Get the replication of a file. * * @param fd The file descriptor. * @return The file replication. */ public int get_file_replication(int fd) { rlock.lock(); try { return native_ceph_get_file_replication(instance_ptr, fd); } finally { rlock.unlock(); } } private static native int native_ceph_get_file_replication(long mountp, int fd); /** * Favor reading from local replicas when possible. * * @param state Enable or disable localized reads. */ public void localize_reads(boolean state) { rlock.lock(); try { native_ceph_localize_reads(instance_ptr, state); } finally { rlock.unlock(); } } private static native int native_ceph_localize_reads(long mountp, boolean on); /** * Get file layout stripe unit granularity. * * @return Stripe unit granularity. */ public int get_stripe_unit_granularity() { rlock.lock(); try { return native_ceph_get_stripe_unit_granularity(instance_ptr); } finally { rlock.unlock(); } } private static native int native_ceph_get_stripe_unit_granularity(long mountp); /** * Get the pool id for the named pool. * * @param name The pool name. * @return The pool id. */ public int get_pool_id(String name) throws CephPoolException { rlock.lock(); try { return native_ceph_get_pool_id(instance_ptr, name); } catch (FileNotFoundException e) { throw new CephPoolException("pool name " + name + " not found"); } finally { rlock.unlock(); } } private static native int native_ceph_get_pool_id(long mountp, String name) throws FileNotFoundException; /** * Get the pool replication factor. * * @param pool_id The pool id. * @return Number of replicas stored in the pool. */ public int get_pool_replication(int pool_id) throws CephPoolException { rlock.lock(); try { return native_ceph_get_pool_replication(instance_ptr, pool_id); } catch (FileNotFoundException e) { throw new CephPoolException("pool id " + pool_id + " not found"); } finally { rlock.unlock(); } } private static native int native_ceph_get_pool_replication(long mountp, int pool_id) throws FileNotFoundException; /** * Get file extent containing a given offset. * * @param fd The file descriptor. * @param offset Offset in file. * @return A CephFileExtent object. */ public CephFileExtent get_file_extent(int fd, long offset) { rlock.lock(); try { return native_ceph_get_file_extent_osds(instance_ptr, fd, offset); } finally { rlock.unlock(); } } private static native CephFileExtent native_ceph_get_file_extent_osds(long mountp, int fd, long offset); /** * Get the fully qualified CRUSH location of an OSD. * * Returns (type, name) string pairs for each device in the CRUSH bucket * hierarchy starting from the given OSD to the root. * * @param osd The OSD device id. * @return List of pairs. */ public Bucket[] get_osd_crush_location(int osd) { rlock.lock(); try { String[] parts = native_ceph_get_osd_crush_location(instance_ptr, osd); Bucket[] path = new Bucket[parts.length / 2]; for (int i = 0; i < path.length; i++) path[i] = new Bucket(parts[i*2], parts[i*2+1]); return path; } finally { rlock.unlock(); } } private static native String[] native_ceph_get_osd_crush_location(long mountp, int osd); /** * Get the network address of an OSD. * * @param osd The OSD device id. * @return The network address. */ public InetAddress get_osd_address(int osd) { rlock.lock(); try { return native_ceph_get_osd_addr(instance_ptr, osd); } finally { rlock.unlock(); } } private static native InetAddress native_ceph_get_osd_addr(long mountp, int osd); }
29,477
25.701087
123
java
null
ceph-main/src/java/java/com/ceph/fs/CephNativeLoader.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; class CephNativeLoader { private static final CephNativeLoader instance = new CephNativeLoader(); private static boolean initialized = false; private static final String JNI_PATH_ENV_VAR = "CEPH_JNI_PATH"; private static final String LIBRARY_NAME = "cephfs_jni"; private static final String LIBRARY_FILE = "libcephfs_jni.so"; private CephNativeLoader() {} public static CephNativeLoader getInstance() { return instance; } public synchronized void loadLibrary() { if (initialized) return; boolean success = false; /* * Allow a Ceph specific environment variable to force * the loading path. */ String path = System.getenv(JNI_PATH_ENV_VAR); try { if (path != null) { System.out.println("Loading libcephfs-jni: " + path); System.load(path); success = true; } else { try { /* * Try default Java loading path(s) */ System.out.println("Loading libcephfs-jni from default path: " + System.getProperty("java.library.path")); System.loadLibrary(LIBRARY_NAME); success = true; } catch (final UnsatisfiedLinkError ule1) { try { /* * Try RHEL/CentOS default path */ path = "/usr/lib64/" + LIBRARY_FILE; System.out.println("Loading libcephfs-jni: " + path); System.load(path); success = true; } catch (final UnsatisfiedLinkError ule2) { /* * Try Ubuntu default path */ path = "/usr/lib/jni/" + LIBRARY_FILE; System.out.println("Loading libcephfs-jni: " + path); System.load(path); success = true; } } } } finally { System.out.println("Loading libcephfs-jni: " + (success ? "Success!" : "Failure!")); } /* * Finish initialization */ CephMount.native_initialize(); initialized = true; } }
3,139
32.404255
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephNotDirectoryException.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.IOException; /** * Component of path is not a directory. */ public class CephNotDirectoryException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephNotDirectoryException. */ public CephNotDirectoryException() { super(); } /** * Construct CephNotDirectoryException with message. */ public CephNotDirectoryException(String s) { super(s); } }
1,538
33.2
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephNotMountedException.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.IOException; /** * Ceph is not mounted. */ public class CephNotMountedException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephNotMountedException. */ public CephNotMountedException() { super(); } /** * Construct CephNotMountedException with message. */ public CephNotMountedException(String s) { super(s); } }
1,511
32.6
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephPoolException.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.IOException; /** * Exception related to Ceph pool. */ public class CephPoolException extends IOException { private static final long serialVersionUID = 1L; /** * Construct CephPoolException. */ public CephPoolException() { super(); } /** * Construct CephPoolException with message. */ public CephPoolException(String s) { super(s); } }
1,492
32.177778
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephStat.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; /** * Holds struct stat fields. */ public class CephStat { /* Set from native */ private boolean is_file; /* S_ISREG */ private boolean is_directory; /* S_ISDIR */ private boolean is_symlink; /* S_ISLNK */ public int mode; public int uid; public int gid; public long size; public long blksize; public long blocks; public long a_time; public long m_time; public boolean isFile() { return is_file; } public boolean isDir() { return is_directory; } public boolean isSymlink() { return is_symlink; } }
1,665
29.851852
78
java
null
ceph-main/src/java/java/com/ceph/fs/CephStatVFS.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; /** * Holds struct statvfs fields. */ public class CephStatVFS { public long bsize; public long frsize; public long blocks; public long bavail; public long files; public long fsid; public long namemax; }
1,321
37.882353
78
java
null
ceph-main/src/java/test/com/ceph/fs/CephAllTests.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.FileNotFoundException; import java.io.IOException; import java.util.UUID; import org.junit.*; import org.junit.runners.Suite; import org.junit.runner.RunWith; import static org.junit.Assert.*; @RunWith( Suite.class ) @Suite.SuiteClasses( { CephDoubleMountTest.class, CephMountCreateTest.class, CephMountTest.class, CephUnmountedTest.class, }) /** * Every Java test class must be added to this list in order to be executed with 'ant test' */ public class CephAllTests{ }
1,601
34.6
91
java
null
ceph-main/src/java/test/com/ceph/fs/CephDoubleMountTest.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.FileNotFoundException; import java.io.IOException; import java.util.UUID; import org.junit.*; import static org.junit.Assert.*; public class CephDoubleMountTest { @Test(expected=CephAlreadyMountedException.class) public void test_double_mount() throws Exception { CephMount mount = new CephMount("admin"); String conf_file = System.getProperty("CEPH_CONF_FILE"); if (conf_file != null) mount.conf_read_file(conf_file); mount.mount(null); try { mount.mount(null); } finally { mount.unmount(); } } }
1,670
35.326087
78
java
null
ceph-main/src/java/test/com/ceph/fs/CephMountCreateTest.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.FileNotFoundException; import org.junit.*; import java.util.UUID; import static org.junit.Assert.*; /* * This tests the mount root dir functionality. It creates an empty * directory in the real root, then it re-mounts the file system * with the empty directory specified as the root. Assertions are * that the "/" in the normal mount is non-empty, and that "/" is * empty in the mount with the empty directory as the root. */ public class CephMountCreateTest { private static String conf_file; @BeforeClass public static void class_setup() throws Exception { conf_file = System.getProperty("CEPH_CONF_FILE"); } private CephMount setupMount(String root) throws Exception { CephMount mount = new CephMount("admin"); if (conf_file != null) mount.conf_read_file(conf_file); mount.conf_set("client_permissions", "0"); mount.mount(root); return mount; } @Test public void test_CephMountCreate() throws Exception { CephMount mount; boolean found; String dir = "libcephfs_junit_" + UUID.randomUUID(); /* root dir has more than one dir */ mount = setupMount("/"); try { mount.rmdir("/" + dir); } catch (FileNotFoundException e) {} mount.mkdirs("/" + dir, 777); String[] subdirs = mount.listdir("/"); found = false; for (String d : subdirs) { if (d.compareTo(dir) == 0) found = true; } assertTrue(found); mount.unmount(); /* changing root to empty dir */ mount = setupMount("/" + dir); subdirs = mount.listdir("/"); found = false; for (String d : subdirs) { found = true; } assertFalse(found); mount.unmount(); /* cleanup */ mount = setupMount("/"); mount.rmdir("/" + dir); mount.unmount(); } }
2,896
30.48913
78
java
null
ceph-main/src/java/test/com/ceph/fs/CephMountTest.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetAddress; import java.util.UUID; import org.junit.*; import static org.junit.Assert.*; import com.ceph.crush.Bucket; /* * Coverage * - Everything is covered in at least success cases. * - l[set,get,remove]xattr are not working */ public class CephMountTest { private static CephMount mount; private static String basedir = null; @BeforeClass public static void setup() throws Exception { mount = new CephMount("admin"); String conf_file = System.getProperty("CEPH_CONF_FILE"); if (conf_file != null) mount.conf_read_file(conf_file); mount.conf_set("client_permissions", "0"); mount.mount(null); basedir = "/libcephfs_junit_" + UUID.randomUUID(); mount.mkdir(basedir, 0777); } @AfterClass public static void destroy() throws Exception { String[] list = mount.listdir(basedir); for (String l : list) System.out.println(l); mount.rmdir(basedir); mount.unmount(); } /* * Helper function to construct a unique path. */ public String makePath() { String path = basedir + "/" + UUID.randomUUID(); return path; } /* * Helper to learn the data pool name, by reading it * from the '/' dir inode. */ public String getRootPoolName() throws Exception { int fd = mount.open("/", CephMount.O_DIRECTORY, 0600); String pool = mount.get_file_pool_name(fd); mount.close(fd); return pool; } /* * Helper function to create a file with the given path and size. The file * is filled with size bytes and the file descriptor is returned. */ public int createFile(String path, int size) throws Exception { int fd = mount.open(path, CephMount.O_RDWR|CephMount.O_CREAT, 0600); byte[] buf = new byte[4096]; int left = size; while (left > 0) { size = Math.min(buf.length, left); long ret = mount.write(fd, buf, size, -1); left -= ret; } return fd; } /* * Helper function to create a unique file and fill it with size bytes. The * file descriptor is returned. */ public int createFile(int size) throws Exception { return createFile(makePath(), size); } @Test(expected=FileNotFoundException.class) public void test_mount_dne() throws Exception { CephMount mount2 = new CephMount("admin"); String conf_file = System.getProperty("CEPH_CONF_FILE"); if (conf_file != null) mount2.conf_read_file(conf_file); mount2.mount("/wlfkjwlekfjwlejfwe"); mount2.unmount(); } /* * Test loading of conf file that doesn't exist. * * FIXME: * Ceph returns -ENOSYS rather than -ENOENT. Correct? */ //@Test(expected=FileNotFoundException.class) @Test public void test_conf_read_file_dne() throws Exception { //mount.conf_read_file("/this_file_does_not_exist"); } /* * Test loading of conf file that isn't valid * * FIXME: implement */ @Test public void test_conf_read_file_invalid() throws Exception { } @Test(expected=NullPointerException.class) public void test_conf_read_file_null() throws Exception { mount.conf_read_file(null); } /* * conf_set/conf_get */ @Test(expected=NullPointerException.class) public void test_conf_set_null_opt() throws Exception { mount.conf_set(null, "value"); } @Test(expected=NullPointerException.class) public void test_conf_set_null_val() throws Exception { mount.conf_set("option", null); } @Test(expected=NullPointerException.class) public void test_conf_get_null_opt() throws Exception { mount.conf_get(null); } @Test public void test_conf() throws Exception { String opt = "log to stderr"; String val1, val2, val3; /* get the current value */ val1 = mount.conf_get(opt); /* * flip the value. this may make some debug information be dumped to the * console when the value becomes true. TODO: find a better config option * to toggle. */ if (val1.compareTo("true") == 0) val2 = "false"; else val2 = "true"; mount.conf_set(opt, val2); /* verify the change */ val3 = mount.conf_get(opt); assertTrue(val3.compareTo(val2) == 0); /* reset to original value */ mount.conf_set(opt, val1); val3 = mount.conf_get(opt); assertTrue(val3.compareTo(val1) == 0); } /* * statfs */ @Test public void test_statfs() throws Exception { CephStatVFS st1 = new CephStatVFS(); mount.statfs("/", st1); /* * FIXME: a better test here is to see if changes to the file system are * reflected through statfs (e.g. increasing number of files). However, it * appears that the updates aren't immediately visible. */ assertTrue(st1.bsize > 0); assertTrue(st1.frsize > 0); assertTrue(st1.blocks > 0); assertTrue(st1.bavail > 0); assertTrue(st1.namemax > 0); } /* * getcwd/chdir */ @Test public void test_getcwd() throws Exception { mount.chdir(basedir); String cwd = mount.getcwd(); assertTrue(cwd.compareTo(basedir) == 0); /* Make sure to reset cwd to root */ mount.chdir("/"); cwd = mount.getcwd(); assertTrue(cwd.compareTo("/") == 0); } @Test(expected=NullPointerException.class) public void test_chdir_null() throws Exception { mount.chdir(null); } @Test(expected=FileNotFoundException.class) public void test_chdir_dne() throws Exception { mount.chdir("/this/path/does/not/exist/"); } /* * FIXME: this test should throw an error (but does not)? */ //@Test(expected=IOException.class) @Test public void test_chdir_not_dir() throws Exception { String path = makePath(); int fd = createFile(path, 1); mount.close(fd); //mount.chdir(path); shouldn't be able to do this? mount.unlink(path); /* * Switch back. Other tests seem to be sensitive to the current directory * being something other than "/". This shouldn't happen once this tests * passes and the call to chdir fails anyway. */ mount.chdir("/"); } /* * listdir */ @Test(expected=NullPointerException.class) public void test_listdir_null() throws Exception { mount.listdir(null); } @Test(expected=FileNotFoundException.class) public void test_listdir_dne() throws Exception { mount.listdir("/this/path/does/not/exist/"); } @Test(expected=IOException.class) public void test_listdir_not_dir() throws Exception { String path = makePath(); int fd = createFile(path, 1); mount.close(fd); try { mount.listdir(path); } finally { mount.unlink(path); } } @Test public void test_listdir() throws Exception { String dir = makePath(); mount.mkdir(dir, 0777); /* test that new directory is empty */ String[] list = mount.listdir(dir); assertTrue(list.length == 0); /* test that new directories are seen */ for (int i = 0; i < 3; i++) mount.mkdir(dir + "/" + i, 777); list = mount.listdir(dir); assertTrue(list.length == 3); /* test that more new directories are seen */ for (int i = 0; i < 30; i++) mount.mkdir(dir + "/x" + i, 777); list = mount.listdir(dir); assertTrue(list.length == 33); /* remove */ for (int i = 0; i < 30; i++) mount.rmdir(dir + "/x" + i); for (int i = 0; i < 3; i++) mount.rmdir(dir + "/" + i); mount.rmdir(dir); } /* * Missing * * ceph_link * ceph_unlink */ /* * rename */ @Test(expected=NullPointerException.class) public void test_rename_null_from() throws Exception { mount.rename(null, "to"); } @Test(expected=NullPointerException.class) public void test_rename_null_to() throws Exception { mount.rename("from", null); } @Test(expected=FileNotFoundException.class) public void test_rename_dne() throws Exception { mount.rename("/this/doesnt/exist", "/this/neither"); } @Test public void test_rename() throws Exception { /* create a file */ String path = makePath(); int fd = createFile(path, 1); mount.close(fd); /* move it to a new name */ String newpath = makePath(); mount.rename(path, newpath); /* verfiy the sizes are the same */ CephStat st = new CephStat(); mount.lstat(newpath, st); assertTrue(st.size == 1); /* remove the file */ mount.unlink(newpath); } /* * mkdir/mkdirs/rmdir */ @Test(expected=IOException.class) public void test_mkdir_exists() throws Exception { String path = makePath(); mount.mkdir(path, 0777); try { mount.mkdir(path, 0777); } finally { mount.rmdir(path); } } @Test(expected=IOException.class) public void test_mkdirs_exists() throws Exception { String path = makePath(); mount.mkdirs(path, 0777); try { mount.mkdirs(path, 0777); } finally { mount.rmdir(path); } } @Test public void test_mkdir() throws Exception { String path = makePath(); mount.mkdir(path, 0777); CephStat st = new CephStat(); mount.lstat(path, st); assertTrue(st.isDir()); mount.rmdir(path); } @Test public void test_mkdirs() throws Exception { String path = makePath(); mount.mkdirs(path + "/x/y", 0777); CephStat st = new CephStat(); mount.lstat(path, st); assertTrue(st.isDir()); mount.lstat(path + "/x", st); assertTrue(st.isDir()); mount.lstat(path + "/x/y", st); assertTrue(st.isDir()); mount.rmdir(path + "/x/y"); mount.rmdir(path + "/x"); mount.rmdir(path); } @Test(expected=FileNotFoundException.class) public void test_rmdir() throws Exception { /* make a new directory */ String path = makePath(); mount.mkdir(path, 0777); CephStat st = new CephStat(); mount.lstat(path, st); assertTrue(st.isDir()); /* remove it */ mount.rmdir(path); /* should not exist now */ mount.lstat(path, st); } /* * readlink * symlink */ @Test public void test_symlink() throws Exception { String oldpath = makePath(); String newpath = makePath(); mount.symlink(oldpath, newpath); CephStat stat = new CephStat(); mount.lstat(newpath, stat); assertTrue(stat.isSymlink()); String symlink = mount.readlink(newpath); assertTrue(symlink.compareTo(oldpath) == 0); mount.unlink(newpath); } /* * lstat */ @Test(expected=NullPointerException.class) public void test_lstat_null_path() throws Exception { mount.lstat(null, new CephStat()); } @Test(expected=NullPointerException.class) public void test_lstat_null_stat() throws Exception { mount.lstat("/path", null); } @Test(expected=FileNotFoundException.class) public void test_lstat_null_dne() throws Exception { mount.lstat("/path/does/not/exist", new CephStat()); } /* * test_stat covers lstat and fstat and stat. * * TODO: create test that for lstat vs stat with symlink follow/nofollow. */ @Test public void test_stat() throws Exception { /* create a new file */ String path = makePath(); int size = 12345; int fd = createFile(path, size); mount.close(fd); /* test some basic info about the new file */ CephStat orig_st = new CephStat(); mount.lstat(path, orig_st); assertTrue(orig_st.size == size); assertTrue(orig_st.blksize > 0); assertTrue(orig_st.blocks > 0); /* now try stat */ CephStat stat_st = new CephStat(); mount.stat(path, stat_st); /* now try fstat */ CephStat other_st = new CephStat(); fd = mount.open(path, CephMount.O_RDWR, 0); mount.fstat(fd, other_st); mount.close(fd); mount.unlink(path); /* compare to fstat results */ assertTrue(orig_st.mode == other_st.mode); assertTrue(orig_st.uid == other_st.uid); assertTrue(orig_st.gid == other_st.gid); assertTrue(orig_st.size == other_st.size); assertTrue(orig_st.blksize == other_st.blksize); assertTrue(orig_st.blocks == other_st.blocks); /* compare to stat results */ assertTrue(orig_st.mode == stat_st.mode); assertTrue(orig_st.uid == stat_st.uid); assertTrue(orig_st.gid == stat_st.gid); assertTrue(orig_st.size == stat_st.size); assertTrue(orig_st.blksize == stat_st.blksize); assertTrue(orig_st.blocks == stat_st.blocks); } /* * stat */ @Test(expected=NullPointerException.class) public void test_stat_null_path() throws Exception { mount.stat(null, new CephStat()); } @Test(expected=NullPointerException.class) public void test_stat_null_stat() throws Exception { mount.stat("/path", null); } @Test(expected=FileNotFoundException.class) public void test_stat_null_dne() throws Exception { mount.stat("/path/does/not/exist", new CephStat()); } @Test(expected=CephNotDirectoryException.class) public void test_enotdir() throws Exception { String path = makePath(); int fd = createFile(path, 1); mount.close(fd); try { CephStat stat = new CephStat(); mount.lstat(path + "/blah", stat); } finally { mount.unlink(path); } } /* * setattr */ @Test(expected=NullPointerException.class) public void test_setattr_null_path() throws Exception { mount.setattr(null, new CephStat(), 0); } @Test(expected=NullPointerException.class) public void test_setattr_null_stat() throws Exception { mount.setattr("/path", null, 0); } @Test(expected=FileNotFoundException.class) public void test_setattr_dne() throws Exception { mount.setattr("/path/does/not/exist", new CephStat(), 0); } @Test public void test_setattr() throws Exception { /* create a file */ String path = makePath(); int fd = createFile(path, 1); mount.close(fd); CephStat st1 = new CephStat(); mount.lstat(path, st1); st1.uid += 1; st1.gid += 1; mount.setattr(path, st1, mount.SETATTR_UID|mount.SETATTR_GID); CephStat st2 = new CephStat(); mount.lstat(path, st2); assertTrue(st2.uid == st1.uid); assertTrue(st2.gid == st1.gid); /* remove the file */ mount.unlink(path); } /* * chmod */ @Test(expected=NullPointerException.class) public void test_chmod_null_path() throws Exception { mount.chmod(null, 0); } @Test(expected=FileNotFoundException.class) public void test_chmod_dne() throws Exception { mount.chmod("/path/does/not/exist", 0); } @Test public void test_chmod() throws Exception { /* create a file */ String path = makePath(); int fd = createFile(path, 1); mount.close(fd); CephStat st = new CephStat(); mount.lstat(path, st); /* flip a bit */ int mode = st.mode; if ((mode & 1) != 0) mode -= 1; else mode += 1; mount.chmod(path, mode); CephStat st2 = new CephStat(); mount.lstat(path, st2); assertTrue(st2.mode == mode); mount.unlink(path); } /* * fchmod */ @Test public void test_fchmod() throws Exception { /* create a file */ String path = makePath(); int fd = createFile(path, 1); CephStat st = new CephStat(); mount.lstat(path, st); /* flip a bit */ int mode = st.mode; if ((mode & 1) != 0) mode -= 1; else mode += 1; mount.fchmod(fd, mode); mount.close(fd); CephStat st2 = new CephStat(); mount.lstat(path, st2); assertTrue(st2.mode == mode); mount.unlink(path); } /* * truncate */ @Test(expected=FileNotFoundException.class) public void test_truncate_dne() throws Exception { mount.truncate("/path/does/not/exist", 0); } @Test(expected=NullPointerException.class) public void test_truncate_null_path() throws Exception { mount.truncate(null, 0); } @Test public void test_truncate() throws Exception { // make file String path = makePath(); int orig_size = 1398331; int fd = createFile(path, orig_size); mount.close(fd); // check file size CephStat st = new CephStat(); mount.lstat(path, st); assertTrue(st.size == orig_size); // truncate and check int crop_size = 333333; mount.truncate(path, crop_size); mount.lstat(path, st); assertTrue(st.size == crop_size); // check after re-open fd = mount.open(path, CephMount.O_RDWR, 0); mount.fstat(fd, st); assertTrue(st.size == crop_size); mount.close(fd); mount.unlink(path); } @Test public void test_open_layout() throws Exception { String path = makePath(); int fd = mount.open(path, CephMount.O_WRONLY|CephMount.O_CREAT, 0, (1<<20), 1, (1<<20), null); mount.close(fd); mount.unlink(path); } /* * open/close */ @Test(expected=FileNotFoundException.class) public void test_open_dne() throws Exception { mount.open("/path/doesnt/exist", 0, 0); } /* * lseek */ @Test public void test_lseek() throws Exception { /* create a new file */ String path = makePath(); int size = 12345; int fd = createFile(path, size); mount.close(fd); /* open and check size */ fd = mount.open(path, CephMount.O_RDWR, 0); long end = mount.lseek(fd, 0, CephMount.SEEK_END); mount.close(fd); mount.unlink(path); assertTrue(size == (int)end); } /* * read/write */ @Test public void test_read() throws Exception { String path = makePath(); int fd = createFile(path, 1500); byte[] buf = new byte[1500]; long ret = mount.read(fd, buf, 1500, 0); assertTrue(ret == 1500); mount.unlink(path); } /* * ftruncate */ @Test public void test_ftruncate() throws Exception { // make file String path = makePath(); int orig_size = 1398331; int fd = createFile(path, orig_size); // check file size CephStat st = new CephStat(); mount.fstat(fd, st); assertTrue(st.size == orig_size); // truncate and check int crop_size = 333333; mount.ftruncate(fd, crop_size); mount.fstat(fd, st); if (st.size != crop_size) { System.err.println("ftruncate error: st.size=" + st.size + " crop_size=" + crop_size); assertTrue(false); } assertTrue(st.size == crop_size); mount.close(fd); // check after re-open fd = mount.open(path, CephMount.O_RDWR, 0); mount.fstat(fd, st); assertTrue(st.size == crop_size); mount.close(fd); mount.unlink(path); } /* * fsync */ @Test public void test_fsync() throws Exception { String path = makePath(); int fd = createFile(path, 123); mount.fsync(fd, false); mount.fsync(fd, true); mount.close(fd); mount.unlink(path); } /* * flock */ @Test public void test_flock() throws Exception { String path = makePath(); int fd = createFile(path, 123); mount.flock(fd, CephMount.LOCK_SH | CephMount.LOCK_NB, 42); mount.flock(fd, CephMount.LOCK_SH | CephMount.LOCK_NB, 43); mount.flock(fd, CephMount.LOCK_UN, 42); mount.flock(fd, CephMount.LOCK_UN, 43); mount.flock(fd, CephMount.LOCK_EX | CephMount.LOCK_NB, 42); try { mount.flock(fd, CephMount.LOCK_SH | CephMount.LOCK_NB, 43); assertTrue(false); } catch(IOException io) {} try { mount.flock(fd, CephMount.LOCK_EX | CephMount.LOCK_NB, 43); assertTrue(false); } catch(IOException io) {} mount.flock(fd, CephMount.LOCK_SH, 42); // downgrade mount.flock(fd, CephMount.LOCK_SH, 43); mount.flock(fd, CephMount.LOCK_UN, 42); mount.flock(fd, CephMount.LOCK_UN, 43); mount.close(fd); mount.unlink(path); } /* * fstat * * success case is handled in test_stat along with lstat. */ /* * sync_fs */ @Test public void test_sync_fs() throws Exception { mount.sync_fs(); } /* * get/set/list/remove xattr */ @Test public void test_xattr() throws Exception { /* make file */ String path = makePath(); int fd = createFile(path, 123); mount.close(fd); /* make xattrs */ String val1 = "This is a new xattr"; String val2 = "This is a different xattr"; byte[] buf1 = val1.getBytes(); byte[] buf2 = val2.getBytes(); mount.setxattr(path, "user.attr1", buf1, buf1.length, mount.XATTR_CREATE); mount.setxattr(path, "user.attr2", buf2, buf2.length, mount.XATTR_CREATE); /* list xattrs */ String[] xattrs = mount.listxattr(path); assertTrue(xattrs.length == 2); int found = 0; for (String xattr : xattrs) { if (xattr.compareTo("user.attr1") == 0) { found++; continue; } if (xattr.compareTo("user.attr2") == 0) { found++; continue; } System.out.println("found unwanted xattr: " + xattr); } assertTrue(found == 2); /* get first xattr by looking up length */ long attr1_len = mount.getxattr(path, "user.attr1", null); byte[] out = new byte[(int)attr1_len]; mount.getxattr(path, "user.attr1", out); String outStr = new String(out); assertTrue(outStr.compareTo(val1) == 0); /* get second xattr assuming original length */ out = new byte[buf2.length]; mount.getxattr(path, "user.attr2", out); outStr = new String(out); assertTrue(outStr.compareTo(val2) == 0); /* remove the attributes */ /* FIXME: the MDS returns ENODATA for removexattr */ /* mount.removexattr(path, "attr1"); xattrs = mount.listxattr(path); assertTrue(xattrs.length == 1); mount.removexattr(path, "attr2"); xattrs = mount.listxattr(path); assertTrue(xattrs.length == 0); */ mount.unlink(path); } /* * get/set/list/remove symlink xattr * * Currently not working. Code is the same as for regular xattrs, so there * might be a deeper issue. */ @Test public void test_get_stripe_unit() throws Exception { String path = makePath(); int fd = createFile(path, 1); assertTrue(mount.get_file_stripe_unit(fd) > 0); mount.close(fd); mount.unlink(path); } @Test public void test_get_repl() throws Exception { String path = makePath(); int fd = createFile(path, 1); assertTrue(mount.get_file_replication(fd) > 0); mount.close(fd); mount.unlink(path); } /* * stripe unit granularity */ @Test public void test_get_stripe_unit_gran() throws Exception { assertTrue(mount.get_stripe_unit_granularity() > 0); } @Test public void test_get_pool_id() throws Exception { String data_pool_name = getRootPoolName(); /* returns valid pool id */ assertTrue(mount.get_pool_id(data_pool_name) >= 0); /* test non-existent pool name */ try { mount.get_pool_id("asdlfkjlsejflkjef"); assertTrue(false); } catch (CephPoolException e) {} } @Test public void test_get_pool_replication() throws Exception { /* test invalid pool id */ try { mount.get_pool_replication(-1); assertTrue(false); } catch (CephPoolException e) {} /* test valid pool id */ String data_pool_name = getRootPoolName(); int poolid = mount.get_pool_id(data_pool_name); assertTrue(poolid >= 0); assertTrue(mount.get_pool_replication(poolid) > 0); } @Test public void test_get_file_pool_name() throws Exception { String data_pool_name = getRootPoolName(); String path = makePath(); int fd = createFile(path, 1); String pool = mount.get_file_pool_name(fd); mount.close(fd); assertTrue(pool != null); /* assumes using default data pool */ assertTrue(pool.compareTo(data_pool_name) == 0); mount.unlink(path); } @Test(expected=IOException.class) public void test_get_file_pool_name_ebadf() throws Exception { String pool = mount.get_file_pool_name(-40); } @Test public void test_get_file_extent() throws Exception { int stripe_unit = 1<<18; String path = makePath(); int fd = mount.open(path, CephMount.O_WRONLY|CephMount.O_CREAT, 0, stripe_unit, 2, stripe_unit*2, null); CephFileExtent e = mount.get_file_extent(fd, 0); assertTrue(e.getOSDs().length > 0); assertTrue(e.getOffset() == 0); assertTrue(e.getLength() == stripe_unit); e = mount.get_file_extent(fd, stripe_unit/2); assertTrue(e.getOffset() == stripe_unit/2); assertTrue(e.getLength() == stripe_unit/2); e = mount.get_file_extent(fd, 3*stripe_unit/2-1); assertTrue(e.getOffset() == 3*stripe_unit/2-1); assertTrue(e.getLength() == stripe_unit/2+1); e = mount.get_file_extent(fd, 3*stripe_unit/2+1); assertTrue(e.getLength() == stripe_unit/2-1); mount.close(fd); mount.unlink(path); } @Test public void test_get_osd_crush_location() throws Exception { Bucket[] path = mount.get_osd_crush_location(0); assertTrue(path.length > 0); for (Bucket b : path) { assertTrue(b.getType().length() > 0); assertTrue(b.getName().length() > 0); } } @Test public void test_get_osd_address() throws Exception { InetAddress addr = mount.get_osd_address(0); assertTrue(addr.getHostAddress().length() > 0); } }
26,218
24.186359
92
java
null
ceph-main/src/java/test/com/ceph/fs/CephUnmountedTest.java
/* * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.ceph.fs; import org.junit.*; import static org.junit.Assert.*; public class CephUnmountedTest { private CephMount mount; @Before public void setup() throws Exception { mount = new CephMount("admin"); } @Test(expected=CephNotMountedException.class) public void test_unmount() throws Exception { mount.unmount(); } @Test(expected=CephNotMountedException.class) public void test_statfs() throws Exception { CephStatVFS stat = new CephStatVFS(); mount.statfs("/a/path", stat); } @Test(expected=CephNotMountedException.class) public void test_getcwd() throws Exception { mount.getcwd(); } @Test(expected=CephNotMountedException.class) public void test_chdir() throws Exception { mount.chdir("/a/path"); } @Test(expected=CephNotMountedException.class) public void test_listdir() throws Exception { mount.listdir("/a/path"); } @Test(expected=CephNotMountedException.class) public void test_unlink() throws Exception { mount.unlink("/a/path"); } @Test(expected=CephNotMountedException.class) public void test_rename() throws Exception { mount.rename("/a/path", "/another/path"); } @Test(expected=CephNotMountedException.class) public void test_mkdirs() throws Exception { mount.mkdirs("/a/path", 0); } @Test(expected=CephNotMountedException.class) public void test_rmdir() throws Exception { mount.rmdir("/a/path"); } @Test(expected=CephNotMountedException.class) public void test_stat() throws Exception { CephStat stat = new CephStat(); mount.stat("/a/path", stat); } @Test(expected=CephNotMountedException.class) public void test_lstat() throws Exception { CephStat stat = new CephStat(); mount.lstat("/a/path", stat); } @Test(expected=CephNotMountedException.class) public void test_setattr() throws Exception { CephStat stat = new CephStat(); mount.setattr("/a/path", stat, 0); } @Test(expected=CephNotMountedException.class) public void test_open() throws Exception { mount.open("/a/path", 0, 0); } @Test(expected=CephNotMountedException.class) public void test_open_layout() throws Exception { mount.open("/a/path", 0, 0, 0, 0, 0, null); } @Test(expected=CephNotMountedException.class) public void test_close() throws Exception { mount.close(0); } @Test(expected=CephNotMountedException.class) public void test_lseek() throws Exception { mount.lseek(0, 0, CephMount.SEEK_CUR); } @Test(expected=CephNotMountedException.class) public void test_read() throws Exception { byte[] buf = new byte[1]; mount.read(0, buf, 1, 0); } @Test(expected=CephNotMountedException.class) public void test_write() throws Exception { byte[] buf = new byte[1]; mount.write(0, buf, 1, 0); } @Test(expected=CephNotMountedException.class) public void test_get_stripe_unit() throws Exception { mount.get_file_stripe_unit(0); } @Test(expected=CephNotMountedException.class) public void test_get_repl() throws Exception { mount.get_file_replication(0); } @Test(expected=CephNotMountedException.class) public void test_get_stripe_unit_gran() throws Exception { mount.get_stripe_unit_granularity(); } @Test(expected=CephNotMountedException.class) public void test_get_pool_id() throws Exception { mount.get_pool_id("data"); } @Test(expected=CephNotMountedException.class) public void test_get_pool_replication() throws Exception { mount.get_pool_replication(1); } @Test(expected=CephNotMountedException.class) public void test_fchmod() throws Exception { mount.fchmod(1, 0); } @Test(expected=CephNotMountedException.class) public void test_chmod() throws Exception { mount.chmod("/foo", 0); } }
4,869
28.515152
78
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/AndroidMethodReturnValueAnalyses.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Collections; import java.util.Set; import soot.Scene; import edu.psu.cse.siis.coal.arguments.LanguageConstraints.Call; import edu.psu.cse.siis.coal.arguments.MethodReturnValueAnalysis; import edu.psu.cse.siis.coal.arguments.MethodReturnValueManager; public class AndroidMethodReturnValueAnalyses { public static void registerAndroidMethodReturnValueAnalyses(final String appName) { MethodReturnValueManager.v().registerMethodReturnValueAnalysis( "java.lang.String getPackageName()", new MethodReturnValueAnalysis() { @Override public Set<Object> computeMethodReturnValues(Call call) { if (Scene .v() .getActiveHierarchy() .isClassSubclassOfIncluding( call.stmt.getInvokeExpr().getMethod().getDeclaringClass(), Scene.v().getSootClass("android.content.Context"))) { return Collections.singleton((Object) appName); } else { return null; } } }); } }
1,840
35.098039
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/AuthorityValueAnalysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import soot.Unit; import soot.Value; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis; import edu.psu.cse.siis.coal.arguments.ArgumentValueManager; public class AuthorityValueAnalysis extends ArgumentValueAnalysis { private static final Object TOP_VALUE = new DataAuthority(Constants.ANY_STRING, Constants.ANY_STRING); @Override public Set<Object> computeArgumentValues(Argument argument, Unit callSite) { ArgumentValueAnalysis stringAnalysis = ArgumentValueManager.v().getArgumentValueAnalysis( Constants.DefaultArgumentTypes.Scalar.STRING); Stmt stmt = (Stmt) callSite; if (!stmt.containsInvokeExpr()) { throw new RuntimeException("Statement " + stmt + " does not contain an invoke expression"); } InvokeExpr invokeExpr = stmt.getInvokeExpr(); Set<Object> hosts = stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[0]), stmt); Set<Object> ports = stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[1]), stmt); Set<Object> result = new HashSet<>(); for (Object host : hosts) { for (Object port : ports) { result.add(new DataAuthority((String) host, (String) port)); } } return result; } @Override public Set<Object> computeInlineArgumentValues(String[] inlineValue) { return new HashSet<Object>(Arrays.asList(inlineValue)); } @Override public Object getTopValue() { return TOP_VALUE; } @Override public Set<Object> computeVariableValues(Value value, Stmt callSite) { throw new RuntimeException("Should not be reached."); } }
2,635
31.146341
97
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/ClassTypeValueAnalysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import soot.Scene; import soot.SootClass; import soot.Unit; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis; public class ClassTypeValueAnalysis extends ArgumentValueAnalysis { private static final String BROADCAST_RECEIVER = "android.content.BroadcastReceiver"; private static final String TOP_VALUE = BROADCAST_RECEIVER; @Override public Set<Object> computeArgumentValues(Argument argument, Unit callSite) { Stmt stmt = (Stmt) callSite; String classType = stmt.getInvokeExpr().getArg(argument.getArgnum()[0]).getType().toString(); if (classType.equals(BROADCAST_RECEIVER)) { List<SootClass> subclasses = Scene.v().getActiveHierarchy() .getSubclassesOf(Scene.v().getSootClass(BROADCAST_RECEIVER)); Set<Object> subclassStrings = new HashSet<>(); for (SootClass sootClass : subclasses) { subclassStrings.add(sootClass.getName()); } if (subclassStrings.size() == 0) { subclassStrings.add(BROADCAST_RECEIVER); } return subclassStrings; } return Collections.singleton((Object) classType); } @Override public Set<Object> computeInlineArgumentValues(String[] inlineValue) { return new HashSet<Object>(Arrays.asList(inlineValue)); } @Override public Object getTopValue() { return TOP_VALUE; } @Override public Set<Object> computeVariableValues(Value value, Stmt callSite) { throw new RuntimeException("Should not be reached."); } }
2,474
31.565789
97
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/ContextValueAnalysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import soot.Unit; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis; public class ContextValueAnalysis extends ArgumentValueAnalysis { private static final String TOP_VALUE = Constants.ANY_STRING; private final String appName; public ContextValueAnalysis(String appName) { this.appName = appName != null ? appName : Constants.ANY_STRING; } @Override public Set<Object> computeArgumentValues(Argument argument, Unit callSite) { return Collections.singleton((Object) this.appName); } @Override public Set<Object> computeInlineArgumentValues(String[] inlineValue) { return new HashSet<Object>(Arrays.asList(inlineValue)); } @Override public Object getTopValue() { return TOP_VALUE; } @Override public Set<Object> computeVariableValues(Value value, Stmt callSite) { throw new RuntimeException("Should not be reached."); } }
1,896
28.640625
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/DataAuthority.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Objects; import edu.psu.cse.siis.coal.Constants; public class DataAuthority { private final String host; private final String port; public DataAuthority(String host, String port) { this.host = host; this.port = port; } public String getHost() { return host; } public String getPort() { return port; } public boolean isPrecise() { return !(Constants.ANY_STRING.equals(host) || Constants.ANY_STRING.equals(port)); } @Override public String toString() { return "host " + host + ", port " + port; } @Override public int hashCode() { return Objects.hash(host, port); } @Override public boolean equals(Object other) { if (!(other instanceof DataAuthority)) { return false; } DataAuthority secondDataAuthority = (DataAuthority) other; return Objects.equals(this.host, secondDataAuthority.host) && Objects.equals(this.port, secondDataAuthority.port); } }
1,738
24.573529
87
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/EntryPointMappingSceneTransformer.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Hierarchy; import soot.MethodOrMethodContext; import soot.Scene; import soot.SceneTransformer; import soot.SootClass; import soot.SootMethod; import soot.Type; import soot.jimple.infoflow.entryPointCreators.AndroidEntryPointConstants; import soot.jimple.toolkits.callgraph.CallGraph; import soot.jimple.toolkits.callgraph.Edge; import soot.jimple.toolkits.callgraph.ReachableMethods; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.PropagationTimers; public class EntryPointMappingSceneTransformer extends SceneTransformer { private final Logger logger = LoggerFactory.getLogger(getClass()); private static SootClass activityClass = null; private static SootClass serviceClass = null; private static SootClass gcmBaseIntentServiceClass = null; private static SootClass receiverClass = null; private static SootClass providerClass = null; private static SootClass applicationClass = null; private final Set<String> entryPointClasses; private final Map<String, Set<String>> callbackMethods; private final Map<SootMethod, Set<String>> entryPointMap; private final Set<SootMethod> visitedEntryPoints = new HashSet<>(); public EntryPointMappingSceneTransformer(Set<String> entryPointClasses, Map<String, Set<String>> callbackMethods, Map<SootMethod, Set<String>> entryPointMap) { this.entryPointClasses = entryPointClasses; this.callbackMethods = callbackMethods; this.entryPointMap = entryPointMap; } @Override protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) { PropagationTimers.v().totalTimer.start(); Timers.v().entryPointMapping.start(); // Set<String> signatures = new HashSet<>(); Map<SootMethod, Set<String>> entryPointMap = this.entryPointMap; if (logger.isDebugEnabled()) { Set<String> difference = new HashSet<>(this.callbackMethods.keySet()); difference.removeAll(entryPointClasses); if (difference.size() == 0) { logger.debug("Difference size is 0"); } else { logger.debug("Difference is " + difference); } } // Set<String> lifecycleMethods = new HashSet<>(); // lifecycleMethods.addAll(AndroidEntryPointConstants.getActivityLifecycleMethods()); // lifecycleMethods.addAll(AndroidEntryPointConstants.getApplicationLifecycleMethods()); // lifecycleMethods.addAll(AndroidEntryPointConstants.getBroadcastLifecycleMethods()); // lifecycleMethods.addAll(AndroidEntryPointConstants.getContentproviderLifecycleMethods()); // lifecycleMethods.addAll(AndroidEntryPointConstants.getServiceLifecycleMethods()); activityClass = Scene.v().getSootClass(AndroidEntryPointConstants.ACTIVITYCLASS); serviceClass = Scene.v().getSootClass(AndroidEntryPointConstants.SERVICECLASS); gcmBaseIntentServiceClass = Scene.v().getSootClass(AndroidEntryPointConstants.GCMBASEINTENTSERVICECLASS); receiverClass = Scene.v().getSootClass(AndroidEntryPointConstants.BROADCASTRECEIVERCLASS); providerClass = Scene.v().getSootClass(AndroidEntryPointConstants.CONTENTPROVIDERCLASS); applicationClass = Scene.v().getSootClass(AndroidEntryPointConstants.APPLICATIONCLASS); if (logger.isDebugEnabled()) { logger.debug(this.callbackMethods.toString()); } for (String entryPoint : entryPointClasses) { // if (!entryPointClasses.contains(entryPoint)) { // System.err.println("Warning: " + entryPoint + " is not an entry point"); // continue; // } SootClass entryPointClass = Scene.v().getSootClass(entryPoint); List<MethodOrMethodContext> callbacks = new ArrayList<>(); // Add methods for component. boolean knownComponentType = addLifecycleMethods(entryPointClass, callbacks); for (SootMethod method : entryPointClass.getMethods()) { String methodName = method.getName(); if (methodName.equals(SootMethod.constructorName) || methodName.equals(SootMethod.staticInitializerName) || !knownComponentType) { callbacks.add(method); } } Set<String> callbackMethodStrings = this.callbackMethods.get(entryPoint); if (callbackMethodStrings != null) { for (String callbackMethodString : callbackMethodStrings) { if (!Scene.v().containsMethod(callbackMethodString)) { if (logger.isWarnEnabled()) { logger.warn("Warning: " + callbackMethodString + " is not in scene"); } continue; } SootMethod method = Scene.v().getMethod(callbackMethodString); // Add constructors for callbacks. for (SootMethod potentialInit : method.getDeclaringClass().getMethods()) { if (potentialInit.isPrivate()) { continue; } String name = potentialInit.getName(); if (name.equals(SootMethod.constructorName)) { addConstructorStack(potentialInit, callbacks); } else if (name.equals(SootMethod.staticInitializerName)) { callbacks.add(potentialInit); } } callbacks.add(method); } } if (logger.isDebugEnabled()) { logger.debug(callbacks.toString()); } ReachableMethods reachableMethods = new ReachableMethods(Scene.v().getCallGraph(), callbacks.iterator(), null); reachableMethods.update(); for (Iterator<MethodOrMethodContext> iter = reachableMethods.listener(); iter.hasNext();) { SootMethod method = iter.next().method(); if (!AnalysisParameters.v().isAnalysisClass(method.getDeclaringClass().getName())) { continue; } if (logger.isDebugEnabled()) { logger.debug(method.toString()); } Set<String> entryPoints = entryPointMap.get(method); if (entryPoints == null) { entryPoints = new HashSet<>(); entryPointMap.put(method, entryPoints); } entryPoints.add(entryPoint); } } if (logger.isDebugEnabled()) { logger.debug("Entry points"); logger.debug(entryPointMap.toString()); CallGraph cg = Scene.v().getCallGraph(); Iterator<Edge> it = cg.listener(); StringBuilder stringBuilder = new StringBuilder("Call graph:\n"); while (it.hasNext()) { soot.jimple.toolkits.callgraph.Edge e = it.next(); stringBuilder.append("" + e.src() + e.srcStmt() + " =" + e.kind() + "=> " + e.tgt() + "\n"); } logger.debug(stringBuilder.toString()); } Timers.v().entryPointMapping.end(); PropagationTimers.v().totalTimer.end(); } private boolean addLifecycleMethods(SootClass entryPointClass, List<MethodOrMethodContext> callbacks) { boolean result = true; Hierarchy hierarchy = Scene.v().getActiveHierarchy(); if (hierarchy.isClassSubclassOf(entryPointClass, activityClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getActivityLifecycleMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, gcmBaseIntentServiceClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getGCMIntentServiceMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, serviceClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getServiceLifecycleMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, receiverClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getBroadcastLifecycleMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, providerClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getContentproviderLifecycleMethods(), callbacks); } else if (hierarchy.isClassSubclassOf(entryPointClass, applicationClass)) { addLifecycleMethodsHelper(entryPointClass, AndroidEntryPointConstants.getApplicationLifecycleMethods(), callbacks); } else { System.err.println("Unknown entry point type: " + entryPointClass); result = false; } return result; } private void addLifecycleMethodsHelper(SootClass entryPointClass, List<String> lifecycleMethods, List<MethodOrMethodContext> callbacks) { for (String lifecycleMethod : lifecycleMethods) { SootMethod method = findMethod(entryPointClass, lifecycleMethod); if (method != null) { callbacks.add(method); } } } /** * Finds a method with the given signature in the given class or one of its super classes * * @param currentClass The current class in which to start the search * @param subsignature The subsignature of the method to find * @return The method with the given signature if it has been found, otherwise null */ protected SootMethod findMethod(SootClass currentClass, String subsignature) { if (currentClass.declaresMethod(subsignature)) { return currentClass.getMethod(subsignature); } if (currentClass.hasSuperclass()) { return findMethod(currentClass.getSuperclass(), subsignature); } return null; } private void addConstructorStack(SootMethod method, List<MethodOrMethodContext> callbacks) { if (visitedEntryPoints.contains(method)) { return; } callbacks.add(method); visitedEntryPoints.add(method); for (Type type : method.getParameterTypes()) { String typeString = type.toString(); if (AnalysisParameters.v().isAnalysisClass(typeString)) { if (Scene.v().containsClass(typeString)) { SootClass sootClass = Scene.v().getSootClass(typeString); for (SootMethod sootMethod : sootClass.getMethods()) { if (sootMethod.getName().equals(SootMethod.constructorName)) { addConstructorStack(sootMethod, callbacks); } } } else if (logger.isWarnEnabled()) { logger.warn("Warning: " + typeString + " is not in scene"); } } } } }
11,115
38.985612
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3Analysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmlpull.v1.XmlPullParserException; import soot.PackManager; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.Transform; import soot.Value; import soot.jimple.StaticFieldRef; import soot.jimple.infoflow.android.data.AndroidMethod; import soot.jimple.infoflow.android.manifest.ProcessManifest; import soot.options.Options; import edu.psu.cse.siis.coal.Analysis; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.FatalAnalysisException; import edu.psu.cse.siis.coal.PropagationSceneTransformer; import edu.psu.cse.siis.coal.PropagationSceneTransformerFilePrinter; import edu.psu.cse.siis.coal.SymbolFilter; import edu.psu.cse.siis.coal.arguments.ArgumentValueManager; import edu.psu.cse.siis.coal.arguments.MethodReturnValueManager; import edu.psu.cse.siis.coal.field.transformers.FieldTransformerManager; import edu.psu.cse.siis.ic3.db.SQLConnection; import edu.psu.cse.siis.ic3.manifest.ManifestPullParser; public class Ic3Analysis extends Analysis<Ic3CommandLineArguments> { private static final String INTENT = "android.content.Intent"; private static final String INTENT_FILTER = "android.content.IntentFilter"; private static final String BUNDLE = "android.os.Bundle"; private static final String COMPONENT_NAME = "android.content.ComponentName"; private static final String ACTIVITY = "android.app.Activity"; private static final String[] frameworkClassesArray = { INTENT, INTENT_FILTER, BUNDLE, COMPONENT_NAME, ACTIVITY }; protected static final List<String> frameworkClasses = Arrays.asList(frameworkClassesArray); private final Logger logger = LoggerFactory.getLogger(getClass()); private Ic3Data.Application.Builder ic3Builder; private Map<String, Ic3Data.Application.Component.Builder> componentNameToBuilderMap; protected String outputDir; protected Writer writer; protected ManifestPullParser detailedManifest; protected Map<String, Integer> componentToIdMap; protected SetupApplication setupApplication; protected String packageName; @Override protected void registerFieldTransformerFactories(Ic3CommandLineArguments commandLineArguments) { Timers.v().totalTimer.start(); FieldTransformerManager.v().registerDefaultFieldTransformerFactories(); } @Override protected void registerArgumentValueAnalyses(Ic3CommandLineArguments commandLineArguments) { ArgumentValueManager.v().registerDefaultArgumentValueAnalyses(); ArgumentValueManager.v().registerArgumentValueAnalysis("classType", new ClassTypeValueAnalysis()); ArgumentValueManager.v().registerArgumentValueAnalysis("authority", new AuthorityValueAnalysis()); ArgumentValueManager.v().registerArgumentValueAnalysis("Set<authority>", new AuthorityValueAnalysis()); ArgumentValueManager.v().registerArgumentValueAnalysis("path", new PathValueAnalysis()); ArgumentValueManager.v().registerArgumentValueAnalysis("Set<path>", new PathValueAnalysis()); } @Override protected void registerMethodReturnValueAnalyses(Ic3CommandLineArguments commandLineArguments) { MethodReturnValueManager.v().registerDefaultMethodReturnValueAnalyses(); } @Override protected void initializeAnalysis(Ic3CommandLineArguments commandLineArguments) throws FatalAnalysisException { long startTime = System.currentTimeMillis() / 1000; outputDir = commandLineArguments.getOutput(); prepareManifestFile(commandLineArguments); if (commandLineArguments.getProtobufDestination() != null) { ic3Builder = Ic3Data.Application.newBuilder(); ic3Builder.setAnalysisStart(startTime); if (commandLineArguments.getSample() != null) { ic3Builder.setSample(commandLineArguments.getSample()); } componentNameToBuilderMap = detailedManifest.populateProtobuf(ic3Builder); } else if (commandLineArguments.getDb() != null) { SQLConnection.init(commandLineArguments.getDbName(), commandLineArguments.getDb(), commandLineArguments.getSsh(), commandLineArguments.getDbLocalPort()); componentToIdMap = detailedManifest.writeToDb(false); } Timers.v().mainGeneration.start(); setupApplication = new SetupApplication(commandLineArguments.getManifest(), commandLineArguments.getInput(), commandLineArguments.getClasspath()); Map<String, Set<String>> callBackMethods; Set<String> entryPointClasses = null; if (detailedManifest == null) { ProcessManifest manifest; try { manifest = new ProcessManifest(commandLineArguments.getManifest()); entryPointClasses = manifest.getEntryPointClasses(); packageName = manifest.getPackageName(); } catch (IOException | XmlPullParserException e) { throw new FatalAnalysisException("Could not process manifest file " + commandLineArguments.getManifest() + ": " + e); } } else { entryPointClasses = detailedManifest.getEntryPointClasses(); packageName = detailedManifest.getPackageName(); } try { callBackMethods = setupApplication.calculateSourcesSinksEntrypoints(new HashSet<AndroidMethod>(), new HashSet<AndroidMethod>(), packageName, entryPointClasses); } catch (IOException e) { logger.error("Could not calculate entry points", e); throw new FatalAnalysisException(); } Timers.v().mainGeneration.end(); Timers.v().misc.start(); // Application package name is now known. ArgumentValueManager.v().registerArgumentValueAnalysis("context", new ContextValueAnalysis(packageName)); AndroidMethodReturnValueAnalyses.registerAndroidMethodReturnValueAnalyses(packageName); if (outputDir != null && packageName != null) { String outputFile = String.format("%s/%s.csv", outputDir, packageName); try { writer = new BufferedWriter(new FileWriter(outputFile, false)); } catch (IOException e1) { logger.error("Could not open file " + outputFile, e1); } } // reset Soot: soot.G.reset(); Map<SootMethod, Set<String>> entryPointMap = commandLineArguments.computeComponents() ? new HashMap<SootMethod, Set<String>>() : null; addSceneTransformer(entryPointMap); if (commandLineArguments.computeComponents()) { addEntryPointMappingSceneTransformer(entryPointClasses, callBackMethods, entryPointMap); } Options.v().set_no_bodies_for_excluded(true); Options.v().set_allow_phantom_refs(true); Options.v().set_output_format(Options.output_format_none); Options.v().set_whole_program(true); Options.v().set_soot_classpath( commandLineArguments.getInput() + File.pathSeparator + commandLineArguments.getClasspath()); Options.v().set_ignore_resolution_errors(true); Options.v().set_process_dir(frameworkClasses); Options.v().setPhaseOption("cg.spark", "on"); // do not merge variables (causes problems with PointsToSets) Options.v().setPhaseOption("jb.ulp", "off"); Options.v().setPhaseOption("jb.uce", "remove-unreachable-traps:true"); Options.v().setPhaseOption("cg", "trim-clinit:false"); Options.v().set_prepend_classpath(true); if (AnalysisParameters.v().useShimple()) { Options.v().set_via_shimple(true); Options.v().set_whole_shimple(true); } Options.v().set_src_prec(Options.src_prec_java); Timers.v().misc.end(); Timers.v().classLoading.start(); for (String frameworkClass : frameworkClasses) { SootClass c = Scene.v().loadClassAndSupport(frameworkClass); Scene.v().forceResolve(frameworkClass, SootClass.BODIES); c.setApplicationClass(); } Scene.v().loadNecessaryClasses(); Timers.v().classLoading.end(); Timers.v().entryPointMapping.start(); Scene.v().setEntryPoints( Collections.singletonList(setupApplication.getEntryPointCreator().createDummyMain())); Timers.v().entryPointMapping.end(); } protected void prepareManifestFile(Ic3CommandLineArguments commandLineArguments) { if (commandLineArguments.getDb() != null || commandLineArguments.getProtobufDestination() != null) { detailedManifest = new ManifestPullParser(); detailedManifest.loadManifestFile(commandLineArguments.getManifest()); } } @Override protected void setApplicationClasses(Ic3CommandLineArguments commandLineArguments) throws FatalAnalysisException { AnalysisParameters.v().addAnalysisClasses( computeAnalysisClasses(commandLineArguments.getInput())); AnalysisParameters.v().addAnalysisClasses(frameworkClasses); } @Override protected void handleFatalAnalysisException(Ic3CommandLineArguments commandLineArguments, FatalAnalysisException exception) { logger.error("Could not process application " + packageName, exception); if (outputDir != null && packageName != null) { try { if (writer == null) { String outputFile = String.format("%s/%s.csv", outputDir, packageName); writer = new BufferedWriter(new FileWriter(outputFile, false)); } writer.write(commandLineArguments.getInput() + " -1\n"); writer.close(); } catch (IOException e1) { logger.error("Could not write to file after failure to process application", e1); } } } @Override protected void processResults(Ic3CommandLineArguments commandLineArguments) throws FatalAnalysisException { System.out.println("\n*****Manifest*****"); System.out.println(detailedManifest.toString()); if (commandLineArguments.getProtobufDestination() != null) { ProtobufResultProcessor resultProcessor = new ProtobufResultProcessor(); try { resultProcessor.processResult(packageName, ic3Builder, commandLineArguments.getProtobufDestination(), commandLineArguments.binary(), componentNameToBuilderMap, AnalysisParameters.v().getAnalysisClasses().size(), writer); } catch (IOException e) { logger.error("Could not process analysis results", e); throw new FatalAnalysisException(); } } else { ResultProcessor resultProcessor = new ResultProcessor(); try { resultProcessor.processResult(commandLineArguments.getDb() != null, packageName, componentToIdMap, AnalysisParameters.v().getAnalysisClasses().size(), writer); } catch (IOException | SQLException e) { logger.error("Could not process analysis results", e); throw new FatalAnalysisException(); } } } @Override protected void finalizeAnalysis(Ic3CommandLineArguments commandLineArguments) { } protected void addSceneTransformer(Map<SootMethod, Set<String>> entryPointMap) { Ic3ResultBuilder resultBuilder = new Ic3ResultBuilder(); resultBuilder.setEntryPointMap(entryPointMap); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); String debugDirPath = System.getProperty("user.home") + File.separator + "debug"; File debugDir = new File(debugDirPath); if (!debugDir.exists()) { debugDir.mkdir(); } String fileName = dateFormat.format(new Date()) + ".txt"; String debugFilename = debugDirPath + File.separator + fileName; String pack = AnalysisParameters.v().useShimple() ? "wstp" : "wjtp"; Transform transform = new Transform(pack + ".ifds", new PropagationSceneTransformer(resultBuilder, new PropagationSceneTransformerFilePrinter(debugFilename, new SymbolFilter() { @Override public boolean filterOut(Value symbol) { return symbol instanceof StaticFieldRef && ((StaticFieldRef) symbol).getField().getDeclaringClass().getName() .startsWith("android.provider"); } }))); if (PackManager.v().getPack(pack).get(pack + ".ifds") == null) { PackManager.v().getPack(pack).add(transform); } else { Iterator<?> it = PackManager.v().getPack(pack).iterator(); while (it.hasNext()) { Object current = it.next(); if (current instanceof Transform && ((Transform) current).getPhaseName().equals(pack + ".ifds")) { it.remove(); break; } } PackManager.v().getPack(pack).add(transform); } } protected void addEntryPointMappingSceneTransformer(Set<String> entryPointClasses, Map<String, Set<String>> entryPointMapping, Map<SootMethod, Set<String>> entryPointMap) { String pack = AnalysisParameters.v().useShimple() ? "wstp" : "wjtp"; Transform transform = new Transform(pack + ".epm", new EntryPointMappingSceneTransformer(entryPointClasses, entryPointMapping, entryPointMap)); if (PackManager.v().getPack(pack).get(pack + ".epm") == null) { PackManager.v().getPack(pack).add(transform); } else { Iterator<?> it = PackManager.v().getPack(pack).iterator(); while (it.hasNext()) { Object current = it.next(); if (current instanceof Transform && ((Transform) current).getPhaseName().equals(pack + ".epm")) { it.remove(); break; } } PackManager.v().getPack(pack).add(transform); } } }
14,560
38.142473
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3CommandLineArguments.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import org.apache.commons.cli.ParseException; import edu.psu.cse.siis.coal.CommandLineArguments; /** * Command line arguments for IC3. */ public class Ic3CommandLineArguments extends CommandLineArguments { private static final String DEFAULT_SSH_PROPERTIES_PATH = "/db/ssh.properties"; private static final String DEFAULT_DATABASE_PROPERTIES_PATH = "/db/cc.properties"; private static final int DEFAULT_LOCAL_PORT = 3369; private static final String DEFAULT_COMPILED_MODEL_PATH = "/res/icc.cmodel"; private static final String DEFAULT_DB_NAME = "cc"; private String manifest; private String db; private String ssh; private String iccStudy; private int dbLocalPort = DEFAULT_LOCAL_PORT; private boolean computeComponents; private String dbName; private String protobufDestination; private boolean binary; private String sample; public String getDbName() { return dbName != null ? dbName : DEFAULT_DB_NAME; } /** * Gets the path to the manifest or .apk file. * * @return The path to the manifest or .apk file. */ public String getManifest() { return manifest; } /** * Gets the path to the database properties file. * * @return The path to the database properties file if IC3 should output its results to a * database, null otherwise. */ public String getDb() { return db; } /** * Gets the path to the SSH properties file. * * @return The path to the SSH properties file if an SSH connection is requested, null otherwise. */ public String getSsh() { return ssh; } public String getIccStudy() { return iccStudy; } /** * Gets the local port to which the database connection should be done. * * @return The local port to connect to. */ public int getDbLocalPort() { return dbLocalPort; } /** * Determines if mappings between ICC-sending locations and the components that contain them * should be computed. * * @return True if the components that contain ICC-sending locations should be determined. */ public boolean computeComponents() { return computeComponents; } /** * Returns the destination protocol buffer file path. * * @return The destination path if any, otherwise null. */ public String getProtobufDestination() { return protobufDestination; } /** * Determines if the output should be binary, in the case of a protobuf output. * * @return True if the output should be binary. */ public boolean binary() { return binary; } /** * Returns the name of the sample. * * @return The sample name, if any, otherwise null. */ public String getSample() { return sample; } /** * Process the command line arguments after initial parsing. This should be called be actually * using the arguments contained in this class. */ public void processCommandLineArguments() { manifest = getOptionValue("apkormanifest"); if (getCompiledModel() == null && getModel() == null) { setCompiledModel(DEFAULT_COMPILED_MODEL_PATH); } iccStudy = getOptionValue("iccstudy"); if (hasOption("db")) { db = getOptionValue("db", DEFAULT_DATABASE_PROPERTIES_PATH); } if (hasOption("ssh")) { ssh = getOptionValue("ssh", DEFAULT_SSH_PROPERTIES_PATH); } if (hasOption("localport")) { try { dbLocalPort = ((Number) getParsedOptionValue("localport")).intValue(); } catch (ParseException e) { e.printStackTrace(); } } if (hasOption("dbname")) { dbName = getOptionValue("dbname", DEFAULT_DB_NAME); } computeComponents = hasOption("computecomponents") || db != null; if (hasOption("protobuf")) { protobufDestination = getOptionValue("protobuf"); } computeComponents = hasOption("computecomponents") || db != null || protobufDestination != null; binary = hasOption("binary"); sample = getOptionValue("sample"); } }
4,758
26.508671
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3CommandLineParser.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import edu.psu.cse.siis.coal.CommandLineParser; /** * Command line parser for IC3. */ public class Ic3CommandLineParser extends CommandLineParser<Ic3CommandLineArguments> { private static final String COPYRIGHT = "Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin\n" + "Systems and Internet Infrastructure Security Laboratory\n"; @Override protected void parseAnalysisSpecificArguments(Options options) { options.addOption(Option.builder("apkormanifest") .desc("Path to the manifest file or the .apk of the application.").hasArg() .argName(".apk or manifest").required().build()); options.addOption(Option.builder("db").desc("Store entry points to database.").hasArg() .optionalArg(true).argName("DB properties file").build()); options.addOption(Option.builder("ssh").desc("Use SSH to connect to the database.").hasArg() .optionalArg(true).argName("SSH properties file").build()); options.addOption(Option.builder("localport").desc("Local DB port to connect to.").hasArg() .type(Number.class).argName("local DB port").build()); options.addOption(Option.builder("protobuf").desc("Destination path for the results.").hasArg() .argName("destination path").build()); options.addOption(Option.builder("sample").desc("Specify a sample name.").hasArg() .argName("sample name").build()); options.addOption(Option.builder("dbname").desc("DB name to connect to.").hasArg() .type(Number.class).argName("DB name").build()); options.addOption("computecomponents", false, "Compute which components each exit point belongs to."); options.addOption("binary", false, "Output a binary protobuf."); } @Override protected void printHelp(Options options) { HelpFormatter formatter = new HelpFormatter(); System.out.println(COPYRIGHT); formatter.printHelp("ic3 -input <Android directory> -classpath <classpath> " + "-apk <path to application .apk> [-computecomponents] " + "[-db <path to DB properties file>] [-ssh <path to SSH properties file>] " + "[-localport <DB local port>] [-modeledtypesonly] [-output <output directory>] " + "[-protobuf <destination path>] [-binary] [-sample <sample name>] " + "[-threadcount <thread count>]", options); } }
3,248
46.086957
99
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3Result.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import soot.SootMethod; import soot.Unit; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.Result; import edu.psu.cse.siis.coal.arguments.Argument; public class Ic3Result extends Result { private final Map<SootMethod, Set<String>> entryPointMap; private final Map<Unit, Map<Integer, Object>> result = new HashMap<>(); private String statistics; public Ic3Result(Map<SootMethod, Set<String>> entryPointMap) { this.entryPointMap = entryPointMap; } @Override public Map<Unit, Map<Integer, Object>> getResults() { return result; } @Override public Object getResult(Unit unit, Argument argument) { Map<Integer, Object> unitResult = result.get(unit); if (unitResult != null) { return unitResult.get(argument.getArgnum()); } return null; } @Override public String getStatistics() { return statistics; } public Map<SootMethod, Set<String>> getEntryPointMap() { return entryPointMap; } @Override public void addResult(Unit unit, int argnum, Object value) { Map<Integer, Object> unitResult = result.get(unit); if (unitResult == null) { unitResult = new HashMap<>(); result.put(unit, unitResult); } unitResult.put(argnum, value); } @Override public void setStatistics(String statistics) { this.statistics = statistics; } public void dump() { System.out.println("*****Result*****"); List<String> results = new ArrayList<>(); boolean outputComponents = entryPointMap != null; for (Map.Entry<Unit, Map<Integer, Object>> entry : result.entrySet()) { Unit unit = entry.getKey(); SootMethod method = AnalysisParameters.v().getIcfg().getMethodOf(unit); String current = method.getDeclaringClass().getName() + "/" + method.getSubSignature() + " : " + unit + "\n"; if (outputComponents) { Set<String> components = entryPointMap.get(method); if (components != null) { current += "Components: " + components + "\n"; } else { current += "Unknown components" + "\n"; } } for (Map.Entry<Integer, Object> entry2 : entry.getValue().entrySet()) { current += " " + entry2.getKey() + " : " + entry2.getValue() + "\n"; } results.add(current); } Collections.sort(results); for (String result : results) { System.out.println(result); } } }
3,360
28.226087
94
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Ic3ResultBuilder.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import soot.MethodOrMethodContext; import soot.Scene; import soot.SootMethod; import soot.Unit; import soot.jimple.InstanceInvokeExpr; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import soot.jimple.toolkits.callgraph.ReachableMethods; import soot.toolkits.graph.ExceptionalUnitGraph; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.Model; import edu.psu.cse.siis.coal.PropagationSolver; import edu.psu.cse.siis.coal.PropagationTimers; import edu.psu.cse.siis.coal.Result; import edu.psu.cse.siis.coal.ResultBuilder; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueManager; import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.PropagationValue; public class Ic3ResultBuilder implements ResultBuilder { private Map<SootMethod, Set<String>> entryPointMap; public void setEntryPointMap(Map<SootMethod, Set<String>> entryPointMap) { this.entryPointMap = entryPointMap; } @Override public Result buildResult(PropagationSolver solver) { PropagationTimers.v().resultGeneration.start(); Result result = new Ic3Result(entryPointMap); List<MethodOrMethodContext> eps = new ArrayList<MethodOrMethodContext>(Scene.v().getEntryPoints()); ReachableMethods reachableMethods = new ReachableMethods(Scene.v().getCallGraph(), eps.iterator(), null); reachableMethods.update(); long reachableStatements = 0; for (Iterator<MethodOrMethodContext> iter = reachableMethods.listener(); iter.hasNext();) { SootMethod method = iter.next().method(); if (method.hasActiveBody() && !Model.v().isExcludedClass(method.getDeclaringClass().getName()) && !method.getDeclaringClass().getName().equals("dummyMainClass") && !method.getDeclaringClass().getName().startsWith("android.support") && !method.getDeclaringClass().getName().startsWith("android.provider")) { ++PropagationTimers.v().reachableMethods; ExceptionalUnitGraph cfg = new ExceptionalUnitGraph(method.getActiveBody()); Stack<Unit> stack = new Stack<>(); for (Unit unit : cfg.getHeads()) { stack.push(unit); } Set<Unit> visited = new HashSet<>(); while (!stack.empty()) { Unit unit = stack.pop(); if (visited.contains(unit)) { continue; } else { visited.add(unit); } for (Unit successor : cfg.getSuccsOf(unit)) { stack.push(successor); } Argument[] arguments = Model.v().getArgumentsForQuery((Stmt) unit); if (arguments != null) { boolean foundModeledType = false; for (Argument argument : arguments) { if (Model.v().isModeledType(argument.getType())) { foundModeledType = true; break; } } Stmt stmt = (Stmt) unit; for (Argument argument : arguments) { if (Model.v().isModeledType(argument.getType())) { int argnum = argument.getArgnum()[0]; BasePropagationValue basePropagationValue; InvokeExpr invokeExpr = stmt.getInvokeExpr(); if (argnum >= 0) { basePropagationValue = solver.resultAt(unit, invokeExpr.getArg(argnum)); } else if (invokeExpr instanceof InstanceInvokeExpr && argnum == -1) { InstanceInvokeExpr instanceInvokeExpr = (InstanceInvokeExpr) invokeExpr; basePropagationValue = solver.resultAt(stmt, instanceInvokeExpr.getBase()); } else { throw new RuntimeException("Unexpected argument number " + argnum + " for invoke expression " + invokeExpr); } if (basePropagationValue instanceof PropagationValue) { PropagationValue propagationValue = (PropagationValue) basePropagationValue; PropagationTimers.v().resultGeneration.end(); PropagationTimers.v().valueComposition.start(); propagationValue.makeFinalValue(solver); PropagationTimers.v().valueComposition.end(); PropagationTimers.v().resultGeneration.start(); result.addResult(unit, argument.getArgnum()[0], propagationValue); } else { result.addResult(unit, argument.getArgnum()[0], basePropagationValue); } } else if (foundModeledType || AnalysisParameters.v().inferNonModeledTypes()) { // We infer non-modeled types if one of the arguments of the query is a modeled type // or if the analysis settings tell us to do so. result.addResult(unit, argument.getArgnum()[0], ArgumentValueManager.v() .getArgumentValues(argument, unit)); } } } } reachableStatements += visited.size(); } PropagationTimers.v().reachableStatements += reachableStatements; } PropagationTimers.v().resultGeneration.end(); return result; } }
6,182
39.149351
100
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/Main.java
package edu.psu.cse.siis.ic3; public class Main { public static void main(String[] args) { Ic3Analysis analysis = new Ic3Analysis(); Ic3CommandLineParser parser = new Ic3CommandLineParser(); Ic3CommandLineArguments commandLineArguments = parser.parseCommandLine(args, Ic3CommandLineArguments.class); if (commandLineArguments == null) { return; } commandLineArguments.processCommandLineArguments(); analysis.performAnalysis(commandLineArguments); } }
498
28.352941
69
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/PathValueAnalysis.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import soot.Unit; import soot.Value; import soot.jimple.Stmt; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis; import edu.psu.cse.siis.coal.arguments.ArgumentValueManager; public class PathValueAnalysis extends ArgumentValueAnalysis { private static final String TOP_VALUE = Constants.ANY_STRING; private static final int PATTERN_LITERAL = 0; private static final int PATTERN_PREFIX = 1; private static final int PATTERN_SIMPLE_GLOB = 2; @Override public Set<Object> computeArgumentValues(Argument argument, Unit callSite) { Argument argument0 = new Argument(argument); argument0.setArgnum(new int[] { argument.getArgnum()[0] }); argument0.setType(Constants.DefaultArgumentTypes.Scalar.STRING); Argument argument1 = new Argument(argument); argument1.setArgnum(new int[] { argument.getArgnum()[1] }); argument1.setType(Constants.DefaultArgumentTypes.Scalar.INT); Set<Object> paths = ArgumentValueManager.v().getArgumentValues(argument0, callSite); Set<Object> types = ArgumentValueManager.v().getArgumentValues(argument1, callSite); Set<Object> result = new HashSet<>(); for (Object path : paths) { for (Object type : types) { result.add(computePathForType((String) path, (Integer) type)); } } return result; } private String computePathForType(String path, int type) { if (type == PATTERN_LITERAL || type == PATTERN_SIMPLE_GLOB) { return path; } else if (type == PATTERN_PREFIX || type == Constants.ANY_INT) { if (path.equals(Constants.ANY_STRING)) { return Constants.ANY_STRING; } else { return String.format("%s(.*)", path); } } else { throw new RuntimeException("Unknown path type: " + type); } } @Override public Set<Object> computeInlineArgumentValues(String[] inlineValue) { return new HashSet<Object>(Arrays.asList(inlineValue)); } @Override public Object getTopValue() { return TOP_VALUE; } @Override public Set<Object> computeVariableValues(Value value, Stmt callSite) { throw new RuntimeException("Should not be reached."); } }
3,071
32.032258
88
java
ic3
ic3-master/src/main/java/edu/psu/cse/siis/ic3/ProtobufResultProcessor.java
/* * Copyright (C) 2015 The Pennsylvania State University and the University of Wisconsin * Systems and Internet Infrastructure Security Laboratory * * Author: Damien Octeau * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.psu.cse.siis.ic3; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import soot.Scene; import soot.SootMethod; import soot.Type; import soot.Unit; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import com.google.protobuf.TextFormat; import edu.psu.cse.siis.coal.AnalysisParameters; import edu.psu.cse.siis.coal.Constants; import edu.psu.cse.siis.coal.Model; import edu.psu.cse.siis.coal.PropagationTimers; import edu.psu.cse.siis.coal.Result; import edu.psu.cse.siis.coal.Results; import edu.psu.cse.siis.coal.arguments.Argument; import edu.psu.cse.siis.coal.field.values.FieldValue; import edu.psu.cse.siis.coal.field.values.ScalarFieldValue; import edu.psu.cse.siis.coal.field.values.TopFieldValue; import edu.psu.cse.siis.coal.values.BasePropagationValue; import edu.psu.cse.siis.coal.values.BottomPropagationValue; import edu.psu.cse.siis.coal.values.PathValue; import edu.psu.cse.siis.coal.values.PropagationValue; import edu.psu.cse.siis.coal.values.TopPropagationValue; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ComponentKind; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ExitPoint; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ExitPoint.Intent; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.ExitPoint.Uri; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.Extra; import edu.psu.cse.siis.ic3.Ic3Data.Application.Component.Instruction; import edu.psu.cse.siis.ic3.Ic3Data.Attribute; import edu.psu.cse.siis.ic3.Ic3Data.AttributeKind; import edu.psu.cse.siis.ic3.manifest.ManifestComponent; import edu.psu.cse.siis.ic3.manifest.ManifestData; import edu.psu.cse.siis.ic3.manifest.ManifestIntentFilter; import edu.psu.cse.siis.ic3.manifest.ManifestPullParser; public class ProtobufResultProcessor { private final Logger logger = LoggerFactory.getLogger(getClass()); private static final String ENTRY_POINT_INTENT = "<INTENT>"; private final int[] preciseNonLinking = { 0, 0, 0, 0 }; private final int[] preciseLinking = { 0, 0, 0, 0 }; private final int[] imprecise = { 0, 0, 0, 0, 0 }; private final int[] top = { 0, 0, 0 }; private final int[] bottom = { 0, 0, 0 }; private final int[] nonexistent = { 0, 0, 0 }; private final int[] preciseFieldValueCount = { 0, 0, 0 }; private final int[] partiallyPreciseFieldValueCount = { 0, 0, 0 }; private final int[] impreciseFieldValueCount = { 0, 0, 0 }; private int intentWithData = 0; private int providerArgument = 0; public void processResult(String appName, Ic3Data.Application.Builder ic3Builder, String protobufDestination, boolean binary, Map<String, Ic3Data.Application.Component.Builder> componentNameToBuilderMap, int analysisClassesCount, Writer writer) throws IOException { for (Result result : Results.getResults()) { ((Ic3Result) result).dump(); analyzeResult(result); writeResultToProtobuf(result, ic3Builder, componentNameToBuilderMap); } ic3Builder.setAnalysisEnd(System.currentTimeMillis() / 1000); String extension = binary ? "dat" : "txt"; String path = String.format("%s/%s_%s.%s", protobufDestination, ic3Builder.getName(), ic3Builder.getVersion(), extension); System.out.println("PATH: " + path); if (binary) { FileOutputStream fileOutputStream = new FileOutputStream(path); ic3Builder.build().writeTo(fileOutputStream); fileOutputStream.close(); } else { FileWriter fileWriter = new FileWriter(path); TextFormat.print(ic3Builder, fileWriter); fileWriter.close(); } Timers.v().totalTimer.end(); String statistics = appName + " " + analysisClassesCount + " " + PropagationTimers.v().reachableMethods + " " + preciseNonLinking[0] + " " + preciseNonLinking[3] + " " + preciseNonLinking[1] + " " + preciseNonLinking[2] + " " + preciseLinking[0] + " " + preciseLinking[3] + " " + preciseLinking[1] + " " + preciseLinking[2] + " " + imprecise[0] + " " + imprecise[3] + " " + imprecise[1] + " " + imprecise[2] + " " + bottom[0] + " " + bottom[1] + " " + bottom[2] + " " + top[0] + " " + top[1] + " " + top[2] + " " + nonexistent[0] + " " + nonexistent[1] + " " + nonexistent[2] + " " + providerArgument + " " + imprecise[4] + " " + preciseFieldValueCount[0] + " " + preciseFieldValueCount[1] + " " + preciseFieldValueCount[2] + " " + partiallyPreciseFieldValueCount[0] + " " + partiallyPreciseFieldValueCount[1] + " " + partiallyPreciseFieldValueCount[2] + " " + impreciseFieldValueCount[0] + " " + impreciseFieldValueCount[1] + " " + impreciseFieldValueCount[2] + " " + PropagationTimers.v().modelParsing.getTime() + " " + Timers.v().mainGeneration.getTime() + " " + Timers.v().entryPointMapping.getTime() + " " + Timers.v().classLoading.getTime() + " " + PropagationTimers.v().problemGeneration.getTime() + " " + PropagationTimers.v().ideSolution.getTime() + " " + PropagationTimers.v().valueComposition.getTime() + " " + PropagationTimers.v().resultGeneration.getTime() + " " + (PropagationTimers.v().soot.getTime() - PropagationTimers.v().totalTimer.getTime()) + " " + (Timers.v().misc.getTime() + PropagationTimers.v().misc.getTime()) + " " + Timers.v().totalTimer.getTime() + "\n"; if (logger.isInfoEnabled()) { logger.info(statistics); } if (writer != null) { writer.write(statistics); writer.close(); } } @SuppressWarnings("unchecked") private void writeResultToProtobuf(Result result, Ic3Data.Application.Builder ic3Builder, Map<String, Component.Builder> componentNameToBuilderMap) { Map<String, Set<Extra>> componentToExtrasMap = new HashMap<>(); Map<String, ManifestComponent> dynamicReceivers = new HashMap<>(); Map<SootMethod, Set<String>> entryPointMap = ((Ic3Result) result).getEntryPointMap(); for (Map.Entry<Unit, Map<Integer, Object>> entry : result.getResults().entrySet()) { Unit unit = entry.getKey(); Argument[] arguments = Model.v().getArgumentsForQuery((Stmt) unit); if (arguments != null) { SootMethod method = AnalysisParameters.v().getIcfg().getMethodOf(unit); Instruction.Builder instructionBuilder = unitToInstructionBuilder(method, unit); Map<String, Object> valueMap = new HashMap<>(arguments.length); Map<Integer, Object> argnumToValueMap = entry.getValue(); for (Argument argument : arguments) { valueMap.put(argument.getProperty("valueType"), argnumToValueMap.get(argument.getArgnum()[0])); } if (valueMap.containsKey("activity")) { insertProtobufExitPoint(instructionBuilder, (BasePropagationValue) valueMap.get("activity"), ComponentKind.ACTIVITY, null, null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("service")) { insertProtobufExitPoint(instructionBuilder, (BasePropagationValue) valueMap.get("service"), ComponentKind.SERVICE, null, null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("receiver")) { insertProtobufExitPoint(instructionBuilder, (BasePropagationValue) valueMap.get("receiver"), ComponentKind.RECEIVER, (Set<String>) valueMap.get("permission"), null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("intentFilter")) { insertDynamicReceiver(dynamicReceivers, (Set<String>) valueMap.get("permission"), (Set<String>) valueMap.get("receiverType"), (BasePropagationValue) valueMap.get("intentFilter"), method, unit); } else if (valueMap.containsKey("provider")) { insertProtobufExitPoint(instructionBuilder, (BasePropagationValue) valueMap.get("provider"), ComponentKind.PROVIDER, null, null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("authority")) { insertProtobufExitPoint(instructionBuilder, getUriValueForAuthorities((Set<String>) valueMap.get("authority")), ComponentKind.PROVIDER, null, null, entryPointMap.get(method), componentNameToBuilderMap); } else if (valueMap.containsKey("pendingIntent")) { BasePropagationValue baseCollectingValue = (BasePropagationValue) valueMap.get("pendingIntent"); String targetType = baseCollectingValue instanceof PropagationValue ? (String) ((PropagationValue) baseCollectingValue) .getValuesForField("targetType").iterator().next().getValue() : null; Set<String> permissions = (Set<String>) valueMap.get("permission"); if (targetType != null) { insertProtobufExitPoint(instructionBuilder, baseCollectingValue, stringToComponentKind(targetType), permissions, null, entryPointMap.get(method), componentNameToBuilderMap); } else { for (ComponentKind target : Arrays.asList(ComponentKind.ACTIVITY, ComponentKind.RECEIVER, ComponentKind.SERVICE)) { insertProtobufExitPoint(instructionBuilder, baseCollectingValue, target, null, null, entryPointMap.get(method), componentNameToBuilderMap); } } } else if (valueMap.containsKey("componentExtra")) { Set<String> extras = (Set<String>) valueMap.get("componentExtra"); if (extras != null) { for (String component : entryPointMap.get(method)) { Set<Extra> existingExtras = componentToExtrasMap.get(component); if (existingExtras == null) { existingExtras = new HashSet<>(); componentToExtrasMap.put(component, existingExtras); } for (String extra : extras) { Extra.Builder extraBuilder = Extra.newBuilder(); extraBuilder.setExtra(extra); extraBuilder.setInstruction(instructionBuilder); existingExtras.add(extraBuilder.build()); } } } } } } for (Map.Entry<String, Set<Extra>> entry : componentToExtrasMap.entrySet()) { componentNameToBuilderMap.get(entry.getKey()).addAllExtras(entry.getValue()); } for (Component.Builder componentBuilder : componentNameToBuilderMap.values()) { ic3Builder.addComponents(componentBuilder); } for (ManifestComponent manifestComponent : dynamicReceivers.values()) { Component.Builder componentBuilder = ManifestPullParser.makeProtobufComponentBuilder(manifestComponent, ComponentKind.DYNAMIC_RECEIVER); componentBuilder.setRegistrationInstruction(unitToInstructionBuilder( manifestComponent.getRegistrationMethod(), manifestComponent.getRegistrationUnit())); ic3Builder.addComponents(componentBuilder); } } private Instruction.Builder unitToInstructionBuilder(SootMethod method, Unit unit) { Instruction.Builder builder = Instruction.newBuilder(); builder.setClassName(method.getDeclaringClass().getName()); builder.setMethod(method.getSignature()); builder.setStatement(unit.toString()); builder.setId(getIdForUnit(unit, method)); return builder; } private void insertProtobufExitPoint(Instruction.Builder instructionBuilder, BasePropagationValue intentValue, ComponentKind componentKind, Set<String> intentPermissions, Integer missingIntents, Set<String> exitPointComponents, Map<String, Component.Builder> componentNameToBuilderMap) { for (String exitPointComponent : exitPointComponents) { ExitPoint.Builder exitPointBuilder = ExitPoint.newBuilder(); exitPointBuilder.setInstruction(instructionBuilder).setKind(componentKind); PropagationValue collectingValue = null; if (intentValue == null || intentValue instanceof TopPropagationValue || intentValue instanceof BottomPropagationValue) { missingIntents = 0; } else if (intentValue instanceof PropagationValue) { collectingValue = (PropagationValue) intentValue; if (collectingValue.getPathValues() == null || collectingValue.getPathValues().size() == 0) { missingIntents = 0; } } else { throw new RuntimeException("Unknown CollectingValue type: " + intentValue.getClass()); } if (missingIntents != null) { exitPointBuilder.setMissing(missingIntents); } else { Set<PathValue> pathValues = collectingValue.getPathValues(); if (pathValues != null) { for (PathValue pathValue : pathValues) { if (componentKind.equals(ComponentKind.PROVIDER)) { exitPointBuilder.addUris(makeProtobufUriBuilder(pathValue)); } else { if (intentPermissions != null && intentPermissions.size() != 0) { for (String intentPermission : intentPermissions) { exitPointBuilder.addIntents(makeProtobufIntentBuilder(pathValue).setPermission( intentPermission)); } } else { exitPointBuilder.addIntents(makeProtobufIntentBuilder(pathValue)); } } } } } Component.Builder componentBuilder = componentNameToBuilderMap.get(exitPointComponent); componentBuilder.addExitPoints(exitPointBuilder); } } private Intent.Builder makeProtobufIntentBuilder(PathValue intentValue) { Intent.Builder intentBuilder = Intent.newBuilder(); insertSingleValuedIntentAttribute(intentValue, "action", AttributeKind.ACTION, intentBuilder); Set<String> categories = intentValue.getSetStringFieldValue("categories"); if (categories != null) { if (categories.contains(null)) { categories.remove(null); categories.add(Constants.NULL_STRING); } intentBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.CATEGORY) .addAllValue(categories)); } Set<Integer> flags = intentValue.getSetFieldValue("flags", Integer.class); if (flags != null) { intentBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.FLAG) .addAllIntValue(flags)); } // String mimeType = intentValue.getSingleStringFieldValue("dataType"); // if (mimeType != null) { // String[] typeParts = mimeType.split("/"); // String type; // String subtype; // if (typeParts.length == 2) { // type = typeParts[0]; // subtype = typeParts[1]; // } else { // type = Constants.ANY_STRING; // subtype = Constants.ANY_STRING; // } // intentBuilder // .addAttributes(Attribute.newBuilder().setKind(AttributeKind.TYPE).addValue(type)); // intentBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.SUBTYPE) // .addValue(subtype)); // } insertSingleValuedIntentAttribute(intentValue, "dataType", AttributeKind.TYPE, intentBuilder); Set<String> extras = intentValue.getSetStringFieldValue("extras"); if (extras != null) { if (extras.contains(null)) { extras.remove(null); extras.add(Constants.NULL_STRING); } intentBuilder.addAttributes(Attribute.newBuilder().setKind(AttributeKind.EXTRA) .addAllValue(extras)); } insertSingleValuedIntentAttribute(intentValue, "clazz", AttributeKind.CLASS, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "package", AttributeKind.PACKAGE, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "scheme", AttributeKind.SCHEME, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "ssp", AttributeKind.SSP, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "uri", AttributeKind.URI, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "path", AttributeKind.PATH, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "query", AttributeKind.QUERY, intentBuilder); insertSingleValuedIntentAttribute(intentValue, "authority", AttributeKind.AUTHORITY, intentBuilder); return intentBuilder; } private void insertSingleValuedIntentAttribute(PathValue pathValue, String attribute, AttributeKind kind, Intent.Builder intentBuilder) { String attributeValue = pathValue.getScalarStringFieldValue(attribute); if (attributeValue != null) { intentBuilder.addAttributes(Attribute.newBuilder().setKind(kind).addValue(attributeValue)); } } private Uri.Builder makeProtobufUriBuilder(PathValue uriValue) { Uri.Builder uriBuilder = Uri.newBuilder(); insertSingleValuedUriAttribute(uriValue, "scheme", AttributeKind.SCHEME, uriBuilder); insertSingleValuedUriAttribute(uriValue, "ssp", AttributeKind.SSP, uriBuilder); insertSingleValuedUriAttribute(uriValue, "uri", AttributeKind.URI, uriBuilder); insertSingleValuedUriAttribute(uriValue, "path", AttributeKind.PATH, uriBuilder); insertSingleValuedUriAttribute(uriValue, "query", AttributeKind.QUERY, uriBuilder); insertSingleValuedUriAttribute(uriValue, "authority", AttributeKind.AUTHORITY, uriBuilder); return uriBuilder; } private void insertSingleValuedUriAttribute(PathValue pathValue, String attribute, AttributeKind kind, Uri.Builder uriBuilder) { String attributeValue = pathValue.getScalarStringFieldValue(attribute); if (attributeValue != null) { uriBuilder.addAttributes(Attribute.newBuilder().setKind(kind).addValue(attributeValue)); } } private ComponentKind stringToComponentKind(String componentKind) { switch (componentKind) { case "a": return ComponentKind.ACTIVITY; case "s": return ComponentKind.SERVICE; case "r": return ComponentKind.RECEIVER; default: throw new RuntimeException("Unknown component kind: " + componentKind); } } private void insertDynamicReceiver(Map<String, ManifestComponent> dynamicReceivers, Set<String> permissions, Set<String> receiverTypes, BasePropagationValue intentFilters, SootMethod method, Unit unit) { if (permissions == null) { permissions = Collections.singleton(null); } for (String receiverType : receiverTypes) { for (String permission : permissions) { insertDynamicReceiverHelper(dynamicReceivers, permission, receiverType, intentFilters, method, unit); } } } private void insertDynamicReceiverHelper(Map<String, ManifestComponent> dynamicReceivers, String permission, String receiverType, BasePropagationValue intentFilters, SootMethod method, Unit unit) { Integer missingIntentFilters; Set<ManifestIntentFilter> manifestIntentFilters; if (intentFilters == null || intentFilters instanceof TopPropagationValue || intentFilters instanceof BottomPropagationValue) { missingIntentFilters = 0; manifestIntentFilters = null; } else if (intentFilters instanceof PropagationValue) { missingIntentFilters = null; PropagationValue collectingValue = (PropagationValue) intentFilters; manifestIntentFilters = new HashSet<>(); for (PathValue branchValue : collectingValue.getPathValues()) { Integer filterPriority = null; FieldValue priorityFieldValue = branchValue.getFieldValue("priority"); if (priorityFieldValue != null) { filterPriority = (Integer) priorityFieldValue.getValue(); } manifestIntentFilters.add(new ManifestIntentFilter(branchValue .getSetStringFieldValue("actions"), branchValue.getSetStringFieldValue("categories"), false, makeManifestData(branchValue), filterPriority)); } } else { throw new RuntimeException("Unknown intent filter type: " + intentFilters.getClass()); } ManifestComponent manifestComponent = dynamicReceivers.get(receiverType); if (manifestComponent == null) { manifestComponent = new ManifestComponent( edu.psu.cse.siis.ic3.db.Constants.ComponentShortType.DYNAMIC_RECEIVER, receiverType, true, true, permission, null, missingIntentFilters, method, unit); dynamicReceivers.put(receiverType, manifestComponent); } manifestComponent.addIntentFilters(manifestIntentFilters); } private List<ManifestData> makeManifestData(PathValue branchValue) { Set<String> mimeTypes = branchValue.getSetStringFieldValue("dataType"); Set<DataAuthority> authorities = branchValue.getSetFieldValue("authorities", DataAuthority.class); Set<String> paths = branchValue.getSetStringFieldValue("paths"); Set<String> schemes = branchValue.getSetStringFieldValue("schemes"); if (mimeTypes == null && authorities == null && paths == null && schemes == null) { return null; } if (mimeTypes == null) { mimeTypes = Collections.singleton(null); } if (authorities == null) { authorities = Collections.singleton(new DataAuthority(null, null)); } if (paths == null) { paths = Collections.singleton(null); } if (schemes == null) { schemes = Collections.singleton(null); } List<ManifestData> result = new ArrayList<>(); for (String mimeType : mimeTypes) { for (DataAuthority dataAuthority : authorities) { for (String dataPath : paths) { for (String scheme : schemes) { result.add(new ManifestData(scheme, dataAuthority.getHost(), dataAuthority.getPort(), dataPath, mimeType)); } } } } return result; } private BasePropagationValue getUriValueForAuthorities(Set<String> authorities) { if (authorities == null) { return null; } PropagationValue collectingValue = new PropagationValue(); for (String authority : authorities) { PathValue branchValue = new PathValue(); ScalarFieldValue schemeFieldValue = new ScalarFieldValue("content"); branchValue.addFieldEntry("scheme", schemeFieldValue); ScalarFieldValue authorityFieldValue = new ScalarFieldValue(authority); branchValue.addFieldEntry("authority", authorityFieldValue); collectingValue.addPathValue(branchValue); } return collectingValue; } private int getIdForUnit(Unit unit, SootMethod method) { int id = 0; for (Unit currentUnit : method.getActiveBody().getUnits()) { if (currentUnit == unit) { return id; } ++id; } return -1; } @SuppressWarnings("unchecked") private void analyzeResult(Result result) { Set<String> nonLinkingFieldNames = new HashSet<>(); nonLinkingFieldNames.add("extras"); nonLinkingFieldNames.add("flags"); nonLinkingFieldNames.add("fragment"); nonLinkingFieldNames.add("query"); for (Map.Entry<Unit, Map<Integer, Object>> entry0 : result.getResults().entrySet()) { Collection<Object> argumentValues = entry0.getValue().values(); boolean top = false; boolean bottom = false; // This is true only if the linking field are precisely known. boolean preciseLinking = true; // This is true only if all fields are precisely known. boolean preciseNonLinking = true; boolean nonexistent = false; boolean intentWithUri = false; boolean entryPointIntent = false; int resultIndex = getResultIndex((Stmt) entry0.getKey()); for (Object value2 : argumentValues) { if (value2 == null) { nonexistent = true; } else if (value2 instanceof TopPropagationValue) { top = true; } else if (value2 instanceof BottomPropagationValue) { bottom = true; } else if (value2 instanceof PropagationValue) { PropagationValue collectingValue = (PropagationValue) value2; for (PathValue branchValue : collectingValue.getPathValues()) { intentWithUri = intentWithUri || isIntentWithUri(branchValue.getFieldMap()); for (Map.Entry<String, FieldValue> entry : branchValue.getFieldMap().entrySet()) { String fieldName = entry.getKey(); FieldValue fieldValue = entry.getValue(); if (fieldValue instanceof TopFieldValue) { if (nonLinkingFieldNames.contains(fieldName)) { preciseNonLinking = false; } else { preciseNonLinking = false; preciseLinking = false; } } else { Object value = fieldValue.getValue(); if (value == null) { continue; } if (value instanceof Set) { Set<Object> values = (Set<Object>) value; if (values.contains(Constants.ANY_STRING) || values.contains(Constants.ANY_CLASS) || values.contains(Constants.ANY_INT) || values.contains(ENTRY_POINT_INTENT) || values.contains("top")) { if (values.contains(ENTRY_POINT_INTENT)) { entryPointIntent = true; } preciseNonLinking = false; if (!nonLinkingFieldNames.contains(fieldName)) { preciseLinking = false; } } } else { if (value.equals(Constants.ANY_STRING) || value.equals(Constants.ANY_CLASS) || value.equals(Constants.ANY_INT) || value.equals(ENTRY_POINT_INTENT) || value.equals("top")) { if (value.equals(ENTRY_POINT_INTENT)) { entryPointIntent = true; } preciseNonLinking = false; if (!nonLinkingFieldNames.contains(fieldName)) { preciseLinking = false; } } } } } } } } if (intentWithUri) { ++this.intentWithData; } if (nonexistent) { if (Scene .v() .getActiveHierarchy() .isClassSubclassOfIncluding( AnalysisParameters.v().getIcfg().getMethodOf(entry0.getKey()).getDeclaringClass(), Scene.v().getSootClass("android.content.ContentProvider"))) { ++this.providerArgument; } else { ++this.nonexistent[resultIndex]; } } else if (top) { ++this.top[resultIndex]; } else if (bottom) { ++this.bottom[resultIndex]; } else if (preciseNonLinking) { if (intentWithUri) { ++this.preciseNonLinking[3]; } else { ++this.preciseNonLinking[resultIndex]; } } else if (preciseLinking) { if (intentWithUri) { ++this.preciseLinking[3]; } else { ++this.preciseLinking[resultIndex]; } } else { if (entryPointIntent) { ++this.imprecise[4]; } else if (intentWithUri) { ++this.imprecise[3]; } else { ++this.imprecise[resultIndex]; } } } } private boolean isIntentWithUri(Map<String, FieldValue> fieldMap) { Set<String> fields = fieldMap.keySet(); if (fields.contains("action") || fields.contains("categories")) { if ((fields.contains("uri") && fieldMap.get("uri") != null && fieldMap.get("uri").getValue() != null) || (fields.contains("path") && fieldMap.get("path") != null && fieldMap.get("path") .getValue() != null) || (fields.contains("scheme") && fieldMap.get("scheme") != null && fieldMap.get("scheme") .getValue() != null) || (fields.contains("ssp") && fieldMap.get("ssp") != null && fieldMap.get("ssp") .getValue() != null)) { return true; } } return false; } private int getResultIndex(Stmt stmt) { InvokeExpr invokeExpr = stmt.getInvokeExpr(); List<Type> types = invokeExpr.getMethod().getParameterTypes(); for (Type type : types) { if (type.toString().equals("android.content.IntentFilter")) { return 1; } else if (type.toString().equals("android.net.Uri")) { return 2; } } return 0; } private boolean containsPartialDefinition(Set<Object> values) { for (Object value : values) { if (value instanceof String && ((String) value).contains("(.*)")) { return true; } } return false; } }
30,081
40.896936
113
java

Dataset Card for "arxiv_java_research_code"

More Information needed

Downloads last month
66