Skip to content

Commit 43ae746

Browse files
committed
Python: Only track modules that are imported
This greatly restricts the set of modules that have a new name under this scheme. One change to the tests was needed, which reflects the fact that the two `main.py` files no longer have the name `main` (which makes sense, since they're never imported under this name).
1 parent 8e11abc commit 43ae746

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

python/ql/src/semmle/python/Module.qll

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,16 +201,31 @@ private string moduleNameFromBase(Container file) {
201201
file instanceof File and result = file.getStem()
202202
}
203203

204+
/**
205+
* Holds if `file` may be transitively imported from a file that may serve as the entry point of
206+
* the execution.
207+
*/
208+
private predicate transitively_imported_from_entry_point(File file) {
209+
file.getExtension().matches("%py%") and
210+
exists(File importer |
211+
importer.getParent() = file.getParent() and
212+
exists(ImportExpr i | i.getLocation().getFile() = importer and i.getName() = file.getStem())
213+
|
214+
importer.maybeExecutedDirectly() or transitively_imported_from_entry_point(importer)
215+
)
216+
}
217+
204218
string moduleNameFromFile(Container file) {
205219
exists(string basename |
206220
basename = moduleNameFromBase(file) and
207221
legalShortName(basename)
208222
|
209223
result = moduleNameFromFile(file.getParent()) + "." + basename
210224
or
211-
// If execution can start in the folder containing this module, then we will assume `file` can
212-
// be imported as an absolute import, and hence return `basename` as a possible name.
213-
file.getParent().(Folder).mayContainEntryPoint() and result = basename
225+
// If `file` is a transitive import of a file that's executed directly, we allow references
226+
// to it by its `basename`.
227+
transitively_imported_from_entry_point(file) and
228+
result = basename
214229
)
215230
or
216231
isPotentialSourcePackage(file) and

python/ql/test/3/library-tests/modules/entry_point/modules.expected

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
| main | hash_bang/main.py:0:0:0:0 | Script main |
2-
| main | name_main/main.py:0:0:0:0 | Module main |
31
| module | hash_bang/module.py:0:0:0:0 | Module module |
42
| module | name_main/module.py:0:0:0:0 | Module module |
53
| package | hash_bang/package:0:0:0:0 | Package package |

0 commit comments

Comments
 (0)