scieee AI-readable full text Open interactive document viewer

Code analysis and instrumentation of submissions for online judges

Esteban Velasco, Luis; Trillo Carreras, Juan; Burgos Sosa, Rodrigo

Abstract

Autonomous practice is fundamental in learning programming and, in the various contexts where programming is taught, automatic problem checkers are extensively used. The so-called online judges offer a repertoire of problems and allow users to submit their solutions for on-the-spot evaluation. The judge receives the code from the user, compiles it, and runs it on different test inputs, then checks that the results match the expected ones. The result of this evaluation for the student is usually limited to a verdict that indicates without details whether the solution is correct or not, takes too long or fails to run. The teacher, on the other hand, sees the raw differences between the program output and the expected output. In programming competitions, this information is more than enough, but more instructive and meaningful feedback would be of great help to the student learning to code. The aim of this work is to apply static code analysis techniques and instrumentation on automatic judges to provide more meaningful feedback to students and teachers. The effectiveness of a small set of tools has been studied on actual submissions from previous years. The conclusions of this analysis, interesting in their own, have helped us decide which checks are most relevant to implement on the judge. We have extended the online judge DOMjudge, (widely used in the Faculty of Computer Science at UCM and other universities) to integrate these checks and include the results in the feedback. This has required modifications to the code and the setup process of the automatic judge, and the development of tools to process the information from those tools

Full text

Análisis de código e instrumentación de los envíos para jueces en línea Code analysis and instrumentation of submissions for online judges Trabajo de Fin de Grado Curso 2023–2024 Autores Luis Esteban Velasco Juan Trillo Carreras Rodrigo Burgos Sosa Director Rubén Rafael Rubio Cuéllar Grado en Ingeniería Informática Facultad de Informática Universidad Complutense de Madrid Análisis de código e instrumentación de los envíos para jueces en línea Code analysis and instrumentation of submissions for online judges Trabajo de Fin de Grado en Ingeniería Informática Autores Luis Esteban Velasco Juan Trillo Carreras Rodrigo Burgos Sosa Director Rubén Rafael Rubio Cuéllar Convocatoria: Junio 2024 Grado en Ingeniería Informática Facultad de Informática Universidad Complutense de Madrid 27 de mayo de 2024 Agradecimientos A nuestras familias por su apoyo, al equipo de DOMjudge y finalmente a Rubén por su entusiasmo y dedicación como tutor de este trabajo de fin de grado. v Resumen Análisis de código e instrumentación de los envíos para jueces en línea La práctica autónoma es fundamental en el aprendizaje de la programación y en los diversos contextos donde se enseña esta disciplina los correctores automáticos de problemas son muy utilizados. Los llamados jueces en línea ofrecen un repertorio de problemas y permiten enviar a los usuarios sus soluciones para que sean evaluadas en el momento. Para evaluarlas, el juez recibe el código del usuario, lo compila y lo ejecuta sobre distintos ejemplos para después comprobar que los resultados coincidan con los esperados. El resultado de esa evaluación para el estudiante se limita habitualmente a un veredicto que indica sin detalles si la solución es correcta o no, tarda demasiado o falla al ejecutarse. El profesor, en cambio, ve las diferencias en bruto entre la salida del programa y la salida esperada. En los concursos de programación, esta información es más que suficiente, pero una retroalimentación más instructiva y significativa sería de gran ayuda para el estudiante que está aprendiendo a programar. El objetivo de este trabajo es aplicar técnicas de análisis de estático e instrumentación en los jueces automáticos para proporcionar retroalimentación más significativa a estudiantes y profesores. Se ha estudiado la efectividad de un pequeño conjunto de herramientas sobre envíos reales de años anteriores. Las conclusiones de este análisis, interesantes por sí mismas, nos han servido para decidir qué comprobaciones son más relevantes para su implementación al juez. Hemos extendido el juez automático DOMjudge, ampliamente utilizado en la facultad de Informática de la UCM y en otras universidades, para integrar estas comprobaciones y mostrar los resultados en la retroalimentación a los estudiantes. Esto ha requerido modificaciones en el código y en el proceso de instalación del juez automático, y el desarrollo de herramientas para procesar la información de los analizadores. Palabras clave Juez en línea, Análisis estático, Instrumentación, C++, DOMjudge vii Abstract Code analysis and instrumentation of submissions for online judges Autonomous practice is fundamental in learning programming and, in the various contexts where programming is taught, automatic problem checkers are extensively used. The so-called online judges offer a repertoire of problems and allow users to submit their solutions for on-the-spot evaluation. The judge receives the code from the user, compiles it, and runs it on different test inputs, then checks that the results match the expected ones. The result of this evaluation for the student is usually limited to a verdict that indicates without details whether the solution is correct or not, takes too long or fails to run. The teacher, on the other hand, sees the raw differences between the program output and the expected output. In programming competitions, this information is more than enough, but more instructive and meaningful feedback would be of great help to the student learning to code. The aim of this work is to apply static code analysis techniques and instrumentation on automatic judges to provide more meaningful feedback to students and teachers. The effectiveness of a small set of tools has been studied on actual submissions from previous years. The conclusions of this analysis, interesting in their own, have helped us decide which checks are most relevant to implement on the judge. We have extended the online judge DOMjudge, (widely used in the Faculty of Computer Science at UCM and other universities) to integrate these checks and include the results in the feedback. This has required modifications to the code and the setup process of the automatic judge, and the development of tools to process the information from those tools. Keywords Online Judge, Static analysis, Instrumentation, C++, DOMjudge ix Chapter 1 Introduction In this section, we present the motivation of this thesis, as well as the proposed objectives, the work plan, a brief overview of this thesis’ organization, and the repositories that include the software developed. Online judges are widely used platforms to test the functionality of code for a specified problem. They are commonly used in competitive programming contests, but their application is also present in many educational institutions. Code is submitted to the online judge, which will be in charge of compiling the code and test it as an approximation to check its correctness; these tests usually involve inputting to the submitted code a predefined input and comparing the output against the expected one. The code can be written in any programming languages the online judge supports. Additional constraints, such as time and memory limits, can be imposed. Users will then receive the judge’s verdict, accepted or wrong answer (the possible verdicts of DOMjudge appear in Section 2.1.1). These are not the only two possible returned verdicts. A submission can be evaluated as inappropriate for a problem if it does not compile or execute correctly. Ensuring that a piece of code satisfies these conditions falls on the users themselves and, in many cases, it can be a non-trivial challenge (specially for those just starting to learn to code). One can attempt to read their code in an attempt to find errors on it. Verify where variables are defined and used, their types, the possible values that they can have during code execution, or what effect they can have on an action. This is, in essence, static analysis of code, and there exist many tools that perform this behavior on a much broader scale. Static analyzers are great tools to find issues in code as it is written, as they do not require to execute the code. They perform a deeper analysis on the code than the one a person could reasonably develop, involving the examination of code structures, syntax, and semantics to detect issues such as inadequately used variables, bug prone code, and violations of coding conventions. They are commonly implemented in code development workflows to detect errors in the code early in the process. In addition to static analyzers, these type of workflows can also use code instrumentation, such as sanitizers, to complement the capabilities of static code analyzers. They are runtime tools (in contrast to static analyzers) and they can identify additional problems in the code, such as memory leaks and undefined 1 2Chapter 1. Introduction behavior. Automatically analyzing a program and explaining its errors is an inherently difficult task, as semantic analysis of the code will generally be undecidable. This is proved by Rice’s theorem, that states that all non-trivial semantic properties of programs are undecidable; non-trivial properties are ones that are neither true for every program nor false for every program. [28] So, it is impossible to assert that a certain program has a property just by looking at how it behaves (its semantics), unless that property is trivial. Moreover, an example of it can be seen in the halting problem, where it is demonstrated that it is impossible to write a program that, receiving as input another program, can decide whether it will stop or not. However, various formal and informal techniques can provide partial answers to some of these problems. These methods have been restricted to the academy or the analysis of critical programs in the industry, but they have recently become more popular with the appearance of tools aimed at the standard programmer and the inclusion of analyzers in the most widely used compilers for languages as popular as C++. For instance, the latest versions of the GNU compiler and Clang include static analyzers to detect errors in the code without executing it, allow programs to be instrumented with predefined checks at runtime, and provide resources for advanced users to easily define their own checks. These positive outcomes could be a welcome addition to the repertoire of possibilities that an online judge offers. 1.1. Motivation In computer science, it is often the case that teaching institutions use practical laboratory lectures as complement to their theoretical ones, specially early in the degree. It is a popular and proven fact that one learns the most by doing, hence there exist many incentives to include online judges in laboratory classes as a main tool to apply this principle. Online judges can aid in structuring an active learning path by which students can apply their acquired knowledge during theoretical lessons to write code that tests their problem-solving skills. The main disadvantage that this kind of tools bring to a studying environment are the often lacking feedback capabilities that they provide. Instructors are, in many cases, in charge of providing assistance to those that are stuck with a doubt or face a never seen before (often technical) compilation or execution error. Generally, it is unrealistic for instructors to be able to attend and satisfy every single student’s needs, as it is to assume that multiple of them can be present simultaneously. There is even the case of no such instructor present or available at a given time, and having a tool as online judges, that are able to provide this sort of aid, despite not as specialized, can offer great value. We, the team behind this thesis, have familiarity with these situations. Understanding the frustration that comes with not grasping the reason for an unaccepted submission or compilation error has determined to be essential in understanding the appreciation for this kind of interaction. There have been multiple reasons to require to perform a manual analysis of the code in order to identify the errors and 1.2. Goals 3 inconsistencies contained in it, essentially performing static analysis; the application of a tool that fulfills this purpose and provides feedback based on it is, in our belief, a valuable addition. A static analyzer is able to find errors in the code without executing it by interpreting the code following symbolic execution. These means that, as the values for the variables are unknown outside execution time, the analyzer must use a symbol to represent these values, and follow the possible paths of execution that the code can take. Each path contains a possible set of values that the variable could be assigned to, and if an error is found in that path, it is reported back to the user. Static analyzers can be an additional step included during compilation or running of code inside an online judge, and its output can be used to generate a feedback message for students accordingly. They would serve well within them, specially when accompanied by additional tools such as code instrumentation. The difference between both tools is that the code needs to be executed for tools performing instrumentation to detect errors inside it. Granted, instrumentation will, in contrast to static analyzers, consume more run time, but being able to customize the possible executions of code inside the judges themselves results in a very attractive proposition. To add to the matter, code analysis is a field that extends to the early days of the appearance of programming languages, which has proven to contain lengthy research and many contributors to its development. Very advanced tools are present with outstanding performance and work behind, that could be implemented for the matter being treated. By combining static analysis and linting with runtime instrumentation, achieving a more comprehensive approach to learning is possible. The challenge resides in applying the right balance to the feedback, and not give too much away as means of granting assistance, which would produce the opposite result that what is trying to be achieved. 1.2. Goals Our main goal is to provide more meaningful feedback to student and instructors using online judges by leveraging on static analysis and instrumentation. At the end, we want to have them integrated into DOMjudge, but to achieve this goal we first need to understand the techniques and tools and find the most appropriate way to use them. We consider the following specific goals: Understand static analysis and instrumentation as provided by several mainstream tools. Study the behavior of a selected set of tools (Clang-Tidy, Cppcheck, ASan, and UBSan) on students submissions and decide which are most useful for meaningful feedback. Extend DOMjudge to allow the execution of code analyzers and instrumented submissions and presents their findings as feedback to students and instructors. 4Chapter 1. Introduction 1.3. Work Plan This project has been developed in two main phases: study phase and implementation phase. The time management for these phases can be seen in figure 1.1. During the initial phase, we studied the necessary concepts in order to understand the basics of how static analyzers and instrumentation work and are used. Following this, a review on the most popular tools in that domain was carried out; this process was fundamental in order to determine which would be included later in the implementation. Once tools were chosen, we analyzed their performance on a set of real student submissions provided by our tutor. This data was part of real student submissions for exams and class problems, which was beneficial because it meant that we could perform an analysis on actual real submissions in order to obtain representative data. Following this, the first step towards being able to implement these tools was understanding how DOMjudge receives a submission and judges it. This is a necessary step to identify the relevant code that should be modified in the upcoming steps. Secondly, we prepared and set up a Docker environment to deploy a DOMjudge instance in our machines for testing and developing purposes. Once the required changes were included in our extended DOMjudge, we put everything done so far together to specify the right checks that should be included for the static analyzers and instrumentation. With this, it remained to verify the functionality of the modified judge with realistic submissions to check the correctness of the implementation and document everything. The following Gantt diagram portrays the time management during this whole process: Figure 1.1: Gantt diagram portraying time management 1.4. Organization of this thesis 5 1.4. Organization of this thesis The general structure of the thesis consists of the following sections: Chapter 1 (Introduction): This part sets out the reasons for carrying out the work, the objectives to be achieved, the organization of the thesis as well as linking the repository of the code used in order to carry out this thesis. Chapter 2 (State of the art): In the state of the art we focus on explaining the platform we are going to modify and the tools that we are going to use for the realization of this thesis. Chapter 3 (Offline analysis on real student submissions): This chapter we analyze the output of the static analyzers and sanitizers on real submissions. We also show the procedure to obtain and analyze the data, the results of that analysis and the conclusions we have arrived to. Chapter 4 (Integration of static and runtime analysis in DOMjudge): this chapter focuses on the modifications made to the DOMjudge platform to integrate the tools necessary for creating the feedback. Chapter 5 (Real use case scenario): In this chapter we show two tests carried out in order to verify the judge’s functionality. Firstly, a prepared submission that serves as proof of concept and, secondly, a made up submission that attempts to be as close to reality as possible .We will show the feedback provided by the judge. Chapter 6 (Conclusions and Future Work): This chapter sets out the discussion of the thesis where we discuss the main problems we encountered and how we solved them, it also shows the conclusions we have arrived to by developing this thesis as well as the future work that could be carried out. Appendix A: table containing an in depth list regarding occurrences of Clang- Tidy diagnostics in submissions, the complete list of relevant checks for the tools of Cppcheck and UBSan as well as a table comparing all the code analysis checks to not overlap them. 1.5. Source code and data repositories We have developed and maintained a series of repositories during the development of this project that collect our efforts to complete the different milestones. The GitHub repository contains the most relevant scripts and code that we have developed for this thesis: scripts for analyzing the information provided by the tools used in the student submissions, scripts for parsing the output of the analyzers, code for creating graphs to understand better the results of the analyzers, the code of the test case and real use case scenarios, the parsers used in DOMjudge to show the feedback, and the composition of the Docker: 6Chapter 1. Introduction https://github.com/Jantri-3/analysis-of-DOMjudge-submissions This repository is the result of a common effort of the whole team. The modifications applied to the source code of DOMjudge to integrate our code analysis features is available in a fork of the official repository at: https://github.com/robu02/DOMjudge The changes made to the source code will be explained in Chapter 4. Moreover, Docker Hub repositories have been used to maintain Docker images of the modified DOMjudge. These images have been created by us from the modified DOMjudge source code. The DOMServer image is at https://hub.docker.com/r/robuso02/domserver and the judgehost image at https://hub.docker.com/r/robuso02/judgehost The creation of these images will be explained in Section 4.4. Chapter 2 State of the art This chapter will cover the main aspects of the thesis to understand online judges platforms and the tools we are going to implement on the DOMjudge in order to give feedback to the student. 2.1. Online judges The online judges were created to facilitate code corrections for instructors at universities, we will start by defining what is an online judge. Online judges are platforms (usually with web interfaces) used for code assessment playing a pivotal role in education, competitive programming, and career training. [21] Online judges take examples of inputs and their corresponding expected output prepared by the instructor, then introduce that same input to the code uploaded and compare the output with the expected one to check if it matches, if it does, the judge qualifies the submission as correct Figure 2.1. Some judges used in education institutions in Spain are DOMjudge and Jutge.org [27]. Jutge.org is developed by the Polytechnic University of Catalonia in order to provide a platform for learning and practicing programming (tailored specifically for their computer science students). As mentioned before, online judges are also used in programming contests. Some notable examples are: the International Collegiate Programming Contest (ICPC) [12], an algorithmic programming contest for college students where DOM- judge is used, and the International Olympiad in Informatics (IOI) [25] contests for secondary and high school students where the judge used is CMS [5], as well as their regional qualifiers. Some other famous online judges are Project Euler [16], Codechef [6]and DMOJ [2]. In this project, we will discuss DOMjudge Figure 2.2, the official judge of the ICPC, as it is the one we use at our University. 7 8Chapter 2. State of the art Figure 2.1: Process of a classic online judge Figure 2.2: DOMjudge logo 2.1.1. DOMjudge As stated on their website, “DOMjudge is a system for running programming contests, like the ICPC regional and world finals programming contests.” [7]. However in the specific case of universities, it is used for giving students assignments and to correct them by an automatic process. These assignments consist of coding problems that read input according to the problem input specification (given by the problem setter) and try to make a code that writes the correct, corresponding output. To return a verdict, the judge performs several steps on a submission. Firstly, it will compile the code (if not an interpreted language), since the users provide their source code. Compilation is performed based on the programming language of the submission, which is specified by the user at the moment of submission. The resulting executable file is then executed, receiving as input the test case specified for the problem attempting to be solved. The output produced during the execution phase is saved to be compared with the expected output of the problem. The output will be parsed to verify its similarity with the solution. The previous steps can be customized to the needs of the problem. DOMjudge 2.1. Online judges 9 offers the possibility of using different compare and run files. If they are not specified, defaults will be used. These special run and compare files allow for specialized and specific checks of requirements or steps for a judgement of a specific problem. To be used, they have to be selected in the special_run and special_compare fields of the problem. Depending on the results of the execution and the expected output, a verdict is obtained for each test case outputs a result, these results are then aggregated into a main verdict. The verdict given can be: WA (Wrong Answer): the code produced an output different from the expected. CE (Compilation Error): the code has compilation errors. RTE (RunTime Exception): during the execution of the code an error has occurred. TLE (Time Limit Exception): the time limit for code execution has been exceeded. AC (ACcepted): the code has finished within the time given and has produced the expected output. Although these verdicts are not frequent, they may sometimes happen: NO (No Output): the code has produced no output. OLE (Output Limit Exception): the code produced too much output. When there’s more than one test case then the results are given based on the first highest priority result. This priority is decided by the administrator of the judge, in our case the priorities are: AC: 1 ≪NO: 10 ≪WA: 30 ≪TLE, RTE, OLE: 99 (maximum priority) Then, if WA and TLE are the results in the test cases of a problem the submission result would be TLE as it has higher priority. Some of the features that DOMjudge provides are: Web interface; Modular system for plugging in languages/compilers and validators; Jury information (such as number of submissions, judging and diffs) and options (rejudge, clarifications, resubmit). However, there is no actual tool provided for giving detailed feedback, they just give the student the result as explained before. The main developers of this platform are Jaap Eldering, Nicky Gerritsen, Keith Johnson, Thijs Kinkhorst, Mart Pluijmaekers, Michael Vasseur and Tobias Werth. 16 Chapter 3. Offline analysis on real student submissions Table 3.1: Number of diagnostics in compiled submissions Name Submission Team Problem performance-avoid-endl 564 263 48 bugprone-narrowing-conversions 481 241 38 performance-for-range-copy 117 64 11 performance-unnecessary-value-param 78 56 21 clang-analyzer-deadcode.DeadStores 57 32 15 bugprone-branch-clone 56 25 12 bugprone-suspicious-semicolon 38 16 11 bugprone-integer-division 32 28 1 clang-analyzer-cplusplus.NewDelete 27 13 2 misc-redundant-expression 14 3 1 clang-analyzer-optin.cplusplus.UninitializedObject 1 1 1 clang-analyzer-optin.cplusplus.UninitializedObject: Uninitialized fields in objects created after a constructor call. In Table 3.1 we show the number of occurrences of each diagnostic within all submissions, shown in the second column. But, in order to avoid any kinds of bias related to diagnostics appearing multiple times within a team or a problem we added two other columns. The third column counts the number of team’s submissions for a problem which contained the diagnostic, and, finally, the fourth column contains the number of problems which have submissions containing the diagnostic. See the full version of Table 3.1 in Table A.1. From the Clang-Tidy statistics we can reach the following conclusions for each of the relevant diagnostics: performance-avoid-endl: It has 18 transitions from TLE to AC and even if the 43% of AC submissions is similar to the 48% global percentage of AC, as it has the most transitions to AC, and it is a nice opportunity to teach students more about IO operations, it would be a nice one to communicate to students using the judge. bugprone-narrowing-conversions: It also has a percentage of AC very similar to global one due to not always being a critical error, but it is probably always unintentional and it also appears in many problems. performance-for-range-copy and performance-unnecessary-value-param: As it was expected the performance do not appear to have relevancy when looking at AC rates or transitions, but as they teach an important lesson and appear many times, we have decided it is beneficial to communicate it to the students 3.3. Code analysis results 17 clang-analyzer-deadcode.DeadStores: It has a high acceptance rate (38%) because it can be due to a leftover value that is not used in the end, but, it has 3 transitions to AC showing it could be helpful to fix errors in some submissions. bugprone-branch-clone: 37% of AC submissions is not significant enough, but as many times it is an error due to copy pasting and then forgetting to change something, it could be communicated with lower priority. bugprone-integer-division: It has a very low acceptance rate, but it only appears in one problem, could be communicated only in some problems, it is also hard to spot if you do not know about it. bugprone-suspicious-semicolon: It is not always a critical error but as it was observed in some submissions it is very tricky to spot. Some students abandon the problem before reaching the solution and others reach the solution with the diagnostic still present, for example a student used a ternary operator within an if statement with a semicolon afterwards, this is why this diagnostic has a low number of transitions to AC. clang-analyzer-cplusplus.NewDelete: It has 0 transitions to AC and a high acceptance rate (48%). This is due to some false positives. misc-redundant-expression: We decided to include this check even though it appears a very small amount of times, due to the fact that it is very tricky to find sometimes, it also has 0 transitions to AC, but that is due to teams abandoning the problem before reaching an AC submission, one team went as far as submitting 11 solutions without reaching an AC. When analyzing those submissions code we noticed that it was a logic error that was easily solvable. clang-analyzer-optin.cplusplus.UninitializedObject: It appears only once in a submission with RTE. 3.3.2. Cppcheck Cppcheck checks that appeared on the dataset are divided into 5 major categories: information : 3 types of checks appeared, just 1 is important style : 24 types appeared, 13 of them relevant ones warning : 7 types appeared, 6 are important performance : 4 types appeared, all of them are didactic error : 8 types appeared, just 3 are actually relevant Cppcheck is a extensive static analyzer as explained in the state of the art. This is why, we can’t find any similar checks between each other. However, as they are quite specific, we can actually join various checks into just one. This can be 18 Chapter 3. Offline analysis on real student submissions seen on the table of appendix C, where we make a detailed explanation of each Cppcheck and Clang.tidy check and determine that 4 different Cppcheck’s checks can be covered by just one Clang-Tidy check. The checks were "redundantCondition", "multiCondition", "duplicateExpression" and "constStatement", all of them could be simplified by letting the Clang-Tidy check misc-redundant-expression localize and explain to the student the flawed coding practice they had. This can be seen on the table in the Appendix A.4. After an exhaustive study of the checks, we have reduced the number of checks raised from 46 different relevant checks to just 27 relevant checks. All relevant checks cover completely different areas or bad practices of the code (this is a result of the said characteristics of Cppcheck). The checks are very diverse and could not be reduced anymore as they did not overlap at all. However, there is actually 3 checks that cover different "areas" of the code but could be easily joined into one, The ShadowVariable,ShadowFunction and ShadowArgument. As the names suggest, they are all related to collisions on named variables/functions or arguments used on an inner function which overlaps the meaning. This is a poor programming practice and must be communicated to the student. The following section is included in the appendix rather than the main text, not due to its lack of relevance, but to avoid overwhelming the reader. Although this information is quite interesting and influential, the format is repetitive as it details all aspects of the errors identified by Cppcheck. Nonetheless, we strongly recommend dedicating time to the Appendix A.2. 3.4. Instrumentation results In this section we show the instrumentation’s results of each of the sanitizers 3.4.1. Memory errors by ASan Out of 3663 submissions, 172 have ASan errors. On average, there were 2.94 errors per submission, for a total of 506 errors. You also have to account that each problem has a different number of test cases and ASan only generates output when faulty code is reached. From the ASan outputs we extracted data about the number of each error’s occurrences, about the distribution of results on each test case with an error, and on each submission with errors, and about the transitions from a not accepted test case to an accepted one when the ASan errors are fixed. They can be found in the repository, again in the analyzer_outputs directory. We can observe that most of the submission with ASan errors were rejected by the online judge 3.2, the errors that appear the most are heap buffer overflows, segmentation faults and stack overflows, and they are not committed by a few teams, nor in a few problems, meaning they are common errors. Runtime exception is the most common result for all errors, except for memory leaks, this is expected as they do not usually cause the program to stop, unless it runs out of memory. Surprisingly, there are submissions with fatal ASan errors that are accepted by the judge. Out of the 20 test cases with errors that were accepted: 2 were memory 3.4. Instrumentation results 19 Figure 3.2: Verdict in test cases and submissions with ASan errors 3.95% AC 1.19% NO TLE 5.34% RTE 66.6% WA 22.92% (a) By test case (506 errors) 1.78% AC 0.58% NO TLE 8.72% RTE 72.67% WA 16.28% (b) By submission (172 errors) leaks and 18 were heap overflows. Although memory leaks should be avoided, they are not errors which should be fatal to the execution of the code, as it should continue execution if there is enough memory. Heap overflows on the other side are more dangerous, they are due to out of bounds accesses, they only stop execution if the position besides the vector is accessible by the program. Even though that position in memory is not supposed to be accessed, the program can luckily read the right value or store it in variable that is not used, hence the solution can still be accepted. 3.4.2. Undefined behavior by UBSan There are 408 submissions out of a total of 4119 that generate one or more ubsan.log files containing the errors. Generating a total of 930 ubsan.log. On average 2.28 files are generated per submission, again there are problems with more cases than others. As we have repeated errors, we need to eliminate any redundancies found. We can find several errors on an assignment repeated on all test cases of said assignment. Within the same case, we can have several errors, so we needed to make a Python script to clean the data. After cleaning the data, we need to make even more modifications to the data in order to associate errors by type as UBSan distinguishes errors by details that the students don’t need (such as “null pointer with base 0xACDFFFFFF. . . ”). We managed to identify 14 different types of errors via regular expressions. The majority of UBSan errors detected result in not accepted qualification by the judge with only 23 out of 408 submissions being accepted.Figure 3.3 UBSan errors detected should be fatal for the execution in any case(meaning that they will probably interrupt the execution). However, the programmer could be “lucky”, as the memory space not intended by the programmer for reading could have a not null value or contain something which made sense in the code. This is the main reason that all UBSan errors raised should be notified to the programmer. It is clearly observed when checking the errors raised that most errors are related to pointers. Although this is expected, it is interesting. Every time a “load of null pointer”, “error reference binding to misaligned ad- 20 Chapter 3. Offline analysis on real student submissions Figure 3.3: Verdict in test cases with UBSan errors Other verdicts 94.36% AC 5.64% dress”, “load of misaligned address”, “store to null pointer”, “store to misaligned address”, “member call on null pointer” and “null pointer passed as argument, which is declared to never be null” appears on the ubsan.log’s generated, the result of the judge on that test case is always RTE . These results make sense as the undefined behavior errors are usually fatal at runtime as said before (at least with the previously mentioned, this is not the case for example with integer overflows). An example of interest is “store to null pointer” which remind us of some errors ASan also detects as “segmentation fault” which is a memory address error. These errors can appear together when running both tools on the same submission. To see the rest of the list of UBSan checks please refer to the Appendix A.3. 3.5. Conclusions After an exhaustive analysis of the static analyzers and the sanitizers we conclude that they are of great importance in order to provide a detailed feedback to the students, with these different tools, Clang-Tidy, Cppcheck, ASan and UBSan, we cover some common mistakes students make with a list of 53 checks. We have observed that a submission having errors detected in the static analysis usually means that the submission was rejected by the judge. Submissions with ASan errors are accepted only 1.74% of the times (3/172), many times due to a runtime exception, as observed in figure 3.2. Submissions with UBSan errors have an even lower percentage of acceptance 0.56% (23/408). Even if they only appear in a low amount of submissions. On the contrary, linters diagnostics appear on a higher number of submissions but are less prone to not being accepted, for example many Clang-Tidy diagnostics have a percentage of acceptance similar to the total submission acceptance rate, which is 42.5%. This means both kind of tools will complement themselves, while instrumentation will detect harsher errors that are easier to detect at runtime, static analysis will detect errors that are easier to detect when analyzing the source code or inefficiencies that when solved will make for a better solution, even if they do not affect the judge’s result. Chapter 4 Integration of static and runtime analysis in DOMjudge This chapter will focus on the actual changes performed to the DOMjudge source code in order to achieve our goal. For this purpose, one has to study and understand how the judge works at a more specialized level in order to see what changes must be performed. There was an abundance of debugging of errors, with their corresponding investigation, to find workarounds to issues in this section. Here, DOMjudge developers’ insights and advice served as great paths to follow to get through them, and they will be discussed and mentioned across the corresponding segment of the chapter. The first and most important step would be to identify the appropriate moment to run the static analyzers and instrumentation during the evaluation process, as well as the location in the file system where the files must be stored. This must not obstruct –or do in the least amount possible– the judge’s tasks that must be carried out in order to evaluate a submission. Once an appropriate method is discovered, the next logical step would be to find the way to get the static and runtime analyses outputs to the user. To carry this task out, Docker has been very helpful. The ease of deployment of Docker containers allowed for a very permissive testing suite that could be dismantled and set back up as many times as necessary. It also allowed for every team member to replicate the development workspace in their machines. In section 4.1, we will focus on dissecting how the DOMjudge works and its structure. We will how a submission is evaluated and the processes that it has to go through. Then, in section 4.2, we will explain the implementation decisions that were made once the submission process was understood, and the necessary changes that had to be applied in the source code to make them happen. During section 4.3, we will then explain how a message for a submission is built based on the outputs generated by the static analyzers and instrumentation that have been implemented and how it is presented to the student. Finally, in section 4.4, we will expose how Docker was used in order to achieve all of this, navigating the process of generating a new image and what was required in order to set up. Also, we will explain the creation of a Docker-compose file that orchestrates the process of initializing all 21 22 Chapter 4. Integration of static and runtime analysis in DOMjudge the containers in an automated manner in order to avoid having to initialize them manually. 4.1. More on the DOMjudge architecture As the first milestone to achieve our goal, understanding how the judge works is crucial. Its components, requirements, which sections are relevant to us, and following the order of calls. The goal is set mainly on understanding how submissions are processed, as other areas of the judge are not relevant for this project. We are interested in knowing what happens from the moment a student presses the submit button, to the moment that the evaluation is returned. Where does it compile? How does it execute? How are the comparisons made between the expected and actual output? The answers to these questions would give us the clues to know where to start making the necessary modifications. Since we’re dealing with static analyzers and sanitizers that have to be included during program compilation, it’s specially relevant for us to know where and how this function is carried out. The DOMjudge version used at the Computer Science School’s laboratories at the time of conducting this project is a rather outdated version. DOMjudge is an open source project and, as such, it is constantly receiving updates thanks to the involvement of its main developers and the participation of volunteer contributors. The source code is published on GitHub,1and the project counts with a Slack workspace for any type of conversation related to it, a mailing list for development discussion –which has been used for this project–, and an inbox for bug reports or feature requests through GitHub or the mailing list itself. It is worth noting that DOMjudge is primarily designed for its use in programming competitions that take place over a period of time that can range from 5 hours to a weekend. As such, its use in the classrooms is not the intended original purpose, and it is important to understand this in order to grasp the reasons for the absence of any learning functionality in its implementation. Our goal will be to modify the source code to achieve features that are not supported and may trigger incompatibilities with the rest of the implementation. We’ll delve deeper into the various issues encountered throughout the project in the sections that follow, as well as some of DOMjudge’s implementation details. 4.1.1. The structure DOMjudge is composed of two main components, DOMserver, a database and at least one judgehost. They are independent components that communicate with each other. DOMjudge is composed of two main components: DOMServer and at least one judgehost. They are independent components that communicate with each other. The different judgehosts are in charge of compiling, running, and checking a submission.2Aside from these, the actual installation also requires a database to store 1https://github.com/DOMjudge/DOMjudge [9] 2https://www.DOMjudge.org/docs/manual/8.2/judging.html#flow-of-a-submission [36] 4.1. More on the DOMjudge architecture 23 all the information available inside the server. It communicates directly with the DOMserver component. DOMserver is short for DOMjudge server, and it is the central entity that runs the DOMjudge web interface and API; which is based on the Contest Control System (CCS) Contest API specification. The DOMserver uses a MySQL or MariaDB database server for information storage. For the development of this project, we will be using a MariaDB database instance. The machine in which the DOMserver is hosted needs to be running Linux or Unix variant and a web server with PHP 8.1 or newer. For the online judge to be functional, it requires one or more judgehosts which will perform the compilation and evaluation of submissions. For our testing purposes, a single judgehost will suffice, as the DOMjudge team recommends one judgehost per twenty teams.3Judgehosts will connect to the server and wait for a solution to be submitted by a team. Submissions are added to a queue from which the different judgehosts will retrieve them and then return a verdict after the required processing has been done on it. The judgedaemon is in charge of managing this inside the judgehosts [30]. 4.1.2. Submission environment The judgedaemon compiles and executes submissions inside a chroot environment4for security reasons – security is a main concern for the team, as arbitrary code is being executed in the system. This environment must contain all the requirements that are needed at compile time to build and run the submissions. DOMjudge also uses Linux Control Groups (or cgroups) and namespaces for process isolation in the judgedaemon. Cgroups allow to allocate resources such as CPU time, memory, and network bandwidth to user-defined groups of tasks.5This aspect limited some of our initial options, since we considered the use of API requests from the scripts ran inside the execution environment in order to retrieve additional useful information, such as the number of attempts for a problem by a team. Due to the fact that the execution environment sees its Internet access limited, the option had to be scraped. 4.1.3. Submission process When a student or team makes a submission, this submission is added to a queue of not yet evaluated submissions. When multiple judgehosts exist, they can all work in parallel to evaluate said queue, each performing their actions on individual submissions. Each submission will be picked by one of the active judgehosts and it 3https://www.DOMjudge.org/docs/manual/8.1/overview.html# requirements-and-contest-planning [36] 4A chroot environment can modify the root directory for a process, restricting access to the rest of the file system. The command being run has no idea that anything outside its environment exists. https://www.howtogeek.com/devops/ what-is-chroot-on-linux-and-how-do-you-use-it/ [15] 5https://access.redhat.com/documentation/es-es/red_hat_enterprise_linux/6/ html/resource_management_guide/ch01 [19] 24 Chapter 4. Integration of static and runtime analysis in DOMjudge will be evaluated by it. To do so, the code traverses the compile,run, and compare phases. Execution is performed in the previously mentioned restricted environment. Restrictions in the environment will be mainly in the form of time and memory usage limitations. The output produced during the execution phase is then compared with the expected output of the solution, which is the second step of this process, where all the compare process takes place. Once completed, processing on the judgehost terminates, and it returns the submission information to the DOMserver, in charge of displaying it to the user. The entire process is orchestrated by the code contained in judgedaemon.main.php, running on every judgehost. It evaluates the submitted assignment and transfers the results back to the DOMServer. The tasks of compiling, running and comparing the code are delegated to a number of different scripts that generate the required files. First, compile.sh is executed to compile the submission. The respective executable path is passed to testcase_run.sh, whose task is to perform run and compare on the submission. Modifications performed to this second file have been key in order to achieve the goals of this project, as it plays a main role during the evaluation process. Before continuing, we will clarify some terms that may induce confusion. The execution or run phase of the submission process is done by executing a script called run. To make it clear as to when we are referring to the run phase and when we are talking about the run script, we will always refer to the phase explicitly. Additionally, the compare phase is performed by executing an executable called run, that is obtained when compiling the source code compare.cc. To avoid confusion between both run files, we will refer to the run produced for the compare phase as compare from this point onwards, and the compare phase will always receive the explicit distinction. The whole process that involves compiling (for our particular case, this will always take place, since we are using C++ code), running and comparing the results is executed for every test case specified for a problem. This is because of the multiple judgehosts can exist at the same time, and the different test cases can be distributed among them. Compilation will only take place once per judgehost, as the judgehost can identify if it already exists a compile output, as means to save time. There can exist one or more than one test cases per problem, and the testcase_run.sh script is run for every one of them. Figure 4.1 visually represents the order of calls that are performed for the described process. 4.1.4. More on files It has been indicated which are the files in charge of performing the different actions, and in this section they will describe the scripts compile.sh,testcase_run.sh, run, and the executable compare further. compile.sh This is an internal DOMjudge script responsible for compiling the student’s assignment and is called from judgehost.main.php. Being internal means that it is not meant to be changed by the users. It accepts as input the absolute path 4.1. More on the DOMjudge architecture 25 Figure 4.1: Submission process sequence diagram. It contains the order in which the calls to the different scripts are made. to the compilation script for the language, the working directory for the evaluation of the current assignment, and the file or files submitted by the student. It returns 0 in case of success, “compiler-error” or “internal-error” if defined, or 1 otherwise. This is the compile wrapper-script called from compile.sh to compile C++ code by default: DEST="$1";shift MEMLIMIT="$1";shift # -x c++: Explicitly set compile language to C++ (no object files or,→ # other languages autodetected by extension) # -Wall: Report all warnings # -O2: Level 2 optimizations (default for speed) # -static: Static link with all libraries # -pipe: Use pipes for communication between stages of compilation,→ g++ -x c++ -Wall -O2 -static -pipe -o "$DEST" "$@" exit $? The compilation script has its own command line interface, taking as input the name of the executable to be created, saved inside the variable DEST, and the maximum memory usage bound, saved inside the variable MEMLIMIT. The result is considered a compilation error if the file with the name of the received executable is not created or if the compile.sh script returns a value other than 0. 32 Chapter 4. Integration of static and runtime analysis in DOMjudge Figure 4.4: Option enabled from DOMjudge settings tion of the test case run that generated it, but we modified this behavior, as the file is currently not being used by the judge. Information regarding this matter was given to us through an email thread with the developers, as for how it stands at the moment of developing this project, it has not yet been included into a main release of DOMjudge, hence it does not appear in its documentation. Anything written during the compare stage to this file will be shown to users of the judge through the text box. The message will contain the parsed output generated for the static analysis and instrumentation, if used. Essentially, it will display the concatenation of all the generated team messages. Unfortunately, this removes the possibility of having a message being shown per test case run. It is a design decision that we would have preferred to avoid, but we consider that having a single message being shown is more convenient for this specific use case than separating it per run. To be able to activate the displaying of messages, a special option must be enabled in the DOMjudge settings as an administrator. When enabling "Show sample output" under "General settings"(see figure 4.4), instructors will be able to use the described features. Again, we would have preferred this feature to not be linked to this option, but the DOMjudge version being used detects when this option is enabled to display the contents of teammessage.txt. 4.3.1. Obtaining the number of tries In order to make the displayed messages more interesting and informative, we decided that it would be a good idea to know the number of attempted submissions for a student/team for a given problem. This would allow us to create a more generic message for the first attempts, hinting as to where the problem could originate from if a submission is incorrect, and guide the students further as the attempts increase. We do not want to give a solution to the problem straight away, but at some point we must guide the student somehow if they cannot find a fix. The number of attempts for a problem can be obtained making an API request to obtain the scoreboard, for what the identifier of the contest is needed; this generated a series of problems involving modifications that had to be applied to the database schema in order to make it accessible inside judgedaemon.main.php. The documentation includes all the available methods of the API in an organized manner. [8, 37, 13] The first part to obtaining the number of tries, involves making the required API request from judgedaemon.main.php to obtain the specific contest. The structure of the returned JSON file for this call is as follows: { 4.3. Providing feedback 33 "event_id":"string", "time":"string", "contest_time":"string", "state": { "started":"string", "ended":"string", "frozen":"string", "thawed":"string", "finalized":"string", "end_of_updates":"string" }, "rows": [ { "rank":0, "team_id":"string", "score": { "num_solved":0, "total_time":0, "total_runtime":0 }, "problems": [ { "label":"string", "problem_id":"string", "num_judged":0, "num_pending":0, "solved":true, "time":0, "first_to_solve":true, "runtime":0, "fastest_submission":true } ] } ] } We are interested in the value contained as a pair of the “num_judged” field. It represents the number of judged submissions for a problem so far, so if the current attempt is the first one, the value retrieved will be 0, and vice versa. To retrieve it, we have to iterate through the teams of a given contest to obtain the current team and then through the problems that have been attempted by the team. What remains is to forward this information to the testcase_run.sh script, which makes it available inside a dedicated file to the compare executable. It was done this way to avoid modifying what the compare executables receive as arguments, in case a customized compare is decided to be used following the default DOMjudge conventions. 34 Chapter 4. Integration of static and runtime analysis in DOMjudge This is the process that involves retrieving the attempts, and we needed the contest identifier to do so; as already said, the API method receives a contest identifier to return the scoreboard. At first, we did not have direct access to this value, being our first idea to obtain it to retrieve the whole list of contests and iterate through it until we found the correct one. A much better solution was provided to us thanks to the team, that is, modifying the JudgeTask entity class to add an additional field containing this information. judgedaemon.main.php includes the JudgeTask entity class, which is used to keep track of the individual judgetasks - judgedaemon.main.php is called once per judging task. It uses this entity class to obtain a number of different values to make requests to the API; the submission ID, for instance. To allow for these changes to be applied, we made modifications to the JudgeTask entity class in order to add a contest_id property index and column to be accessed from judgedaemon.main.php. In order to successfully update the contest identifier, we included a line in the function in charge of adding the current submission identifier to also add the current contest identifier to the entity: public function getSubmitid(): ?int { $this->contestidjt = $this->submission?-%>getContest()->getCid();,→ return $this->submission?->getSubmitid(); } This line gets the current contest from the submission and assigns its id to the JudgeTask entry. Next, we had to go to the Symfony6directory and execute the appropriate commands in order to migrate the database, that is, reflect the changes made to JudgeTask on the actual database. The base directory for Symfony is located at /webapp in the DOMserver. All database migrations are located inside the directory webapp/migrations. A new file was generated in this directory with the corresponding change to the database schema. Some debugging was required during this process to understand some other changes that had to be made to allow this to happen. The most relevant change was modifying the file .env.local, adding an updated environment variable value that is required by Symfony as per their documentation.7The file now contained DATABASE_URL=mysql://DOMjudge:[email protected]:3306/DOMjudge?serve ⌋ rVersion=mariadb-10.11.6,→ This line specifies the database URL, with the database user, password, host and port number, as well as the database used and its version in the following format: 6Symfony is an open-source PHP framework. It is used to develop software that simplifies the web design processhttps://builtin.com/software-engineering-perspectives/symfony [41] 7https://symfony.com/doc/current/doctrine.html [29] 4.4. Preparations and Setup 35 mysql://<user>:<password>@<host>:<port>/<database>?serverVersion ⌋ =<version>,→ All the fields can be found in etc/dbpasswords.secret except for the version, which is obtained by executing mysql -V in the server container. Once this was applied, we could successfully make the desired migration, reflecting the changes in the database. 4.3.2. Generating the message The last step to forward a complete message is actually parsing the static analyzers output and putting the pieces together. This process is carried out from the compare script, as it is now the latter stage for all the previous processes. It has access to the number of attempts, the static analyzers output, and the teammessage.txt file that is later used to forward the message to the students. To achieve this, we decided that the best approach in our case would be to reuse part of the Python scripts that we already had developed for the analysis in section 3.2, and make the appropriate call from the compare script to run these parser scripts. The first step was including the new scripts in DOMjudge, and make sure that they are included inside our image. This was done by adding them inside the same directory as the testcase_run.sh script and adding them to the Makefile (judge/Makefile). install-judgehost: $(INSTALL_PROG)-t $(DESTDIR)$(judgehost_libjudgedir)\ compile.sh build_executable.sh testcase_run.sh chroot-startstop.sh \,→ check_diff.sh evict version_check.sh python_script.py What remains now is to forward these scripts to the compare working directory, which is simply achieved from the testcase_run.sh file as it has access to it. Each script will only be executed if the option that selects their respective analysis tool is indicated in the header of a test case. They will parse the output file generated by the tool and output a message to the teammessage.txt file. For instance, the script used to generate the message for ClangTidy is called parse_clang.py, and the file that it expects as input is called clangtidy.yaml, which is created when Clangtidy runs its analysis on the source code of the submission. 4.4. Preparations and Setup We have explained everything with regard to the implementation up to this point, but not how they were applied. All the changes were tested in a functional DOM- judge environment. Diving a bit into all the DOMjudge offerings and repositories, we discovered that the developers maintain a Docker8image with all the require- 8Docker is an open platform for developing, shipping, and running applications. It provides the ability to run an application in an isolated environment called a container [18]. 36 Chapter 4. Integration of static and runtime analysis in DOMjudge ments in order to deploy a functional DOMjudge locally. It is specially intended for those that want to collaborate with the project and need a testing environment, so it worked perfectly; with an appropriate use of it, it allowed us to have the same working environment replicated on all of our machines. These images are available in the public Docker repository, Docker Hub, as DOMjudge/domserver and DOMjudge/judgehost. Before being able to start the containers for these images, an instance of a MariaDB database must exist beforehand. Fortunately, it is very easy to set up using Docker, and the Docker Hub page of the DOMjudge itself explains the steps that must be followed to deploy it, granting the commands that must be executed. In order to be able to run these containers locally, Docker is required to be installed in the machines. An important aspect to consider is that, as previously mentioned, DOMjudge uses Linux Control Groups or cgroups for process isolation in the judgedaemon. So, to enable cgroup requirements for DOMjudge, we have to add cgroup memory and swap accounting to the boot option. Additionally, modern Linux distributions have cgroup v2 enabled by default, and we have to specify that we want to boot the host into cgroup v19, which is the only one supported by DOMjudge. All the previously mentioned can be achieved by adding the following in /etc/default/grub: GRUB_CMDLINE_LINUX_DEFAULT="quiet cgroup_enable=memory swapaccount=1 isolcpus=2 systemd.unified_cgroup_hierarchy=0",→ The content of this file indicates to the system bootloader at system boot time what arguments have to be passed to the system kernel to configure the system. A bootloader is a program which enables the selection of the installed operating system or kernel to be loaded at system boot time. It also allows the user to pass arguments to the kernel10. So, the code in the previous step is executed during the boot process to apply the DOMjudge requirements: booting into cgroup v2. In addition to this, cgroup memory and swap accounting has also been added as per the recommendations in the documentation [36]. The key GRUB_CMDLINE_LINUX_DEFAULT lists commandline arguments to add only to the default menu entry. [11] Commandline arguments are additional inputs forwarded to a command in order to specify files to used, options to be enabled, or any other parameter required for a command to execute properly. Many are optional, and are used to specify a behavior for a command other than the default one. [38] 4.4.1. Initializing the containers Having this now configured, we can initialize the different containers in order to have a functional DOMjudge installation. The first step in the process involves 9https://www.DOMjudge.org/docs/manual/main/install-judgehost.html# linux-control-groups [36] 10https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/5/ html/installation_guide/s1-grub-whatis [20] 4.4. Preparations and Setup 37 initializing the database, since the domserver requires that it exists beforehand. This can be achieved by running the commands contained in the guide that the DOMjudge team has developed. By default, the configuration exposes the server on port 13306 on the local machine. Once the database is created, a domserver instance can be started, indicating that we want to use the existing running database to store information. Initially, the domserver will have no user aside from the administrator account, and no problems or contests available. Lastly, as many judgehosts as the installation requires can be initialized. Judgehosts will be linked to the domserver instance and receive a different hostname for each. This is everything necessary in order to have a functional DOMServer ran using Docker. The web interface can be accessed on http://localhost:12345/ , allowing only for admin login at first, as no other account is provided by default. Files can be edited directly from the running container by starting an interactive shell session. A main consideration is that the judge at this stage lacks additional packages that could be necessary in order to make effective modifications, such as Vim as an editing software. They have to be installed in order to make them available to be used. Other packages and dependencies required are those needed in order to run the static analyzers, Clang-Tidy and Cppcheck, as GCC comes preinstalled. Installing a text editor directly, for example, is straightforward, as it can be directly installed through the interactive shell session, along with any other desired package. In order to be able to run the static analyzers, we have to make them accessible from the chroot environment, as submissions are evaluated and executed there. To do so, we can execute the script ´bin/dj_run_chroot, which runs an interactive shell or a command inside the chroot. Since apt is available inside the chroot, we can install the required packages using it. The name of the packages that have to be installed in order to make the static analyzers usable are: clang-tidy and cppcheck, and the following command installs them: apt-get update && apt-get install -y clang-tidy cppcheck This is not the most convenient way to do so, and it can be configured to install everything required beforehand, but it will suffice for our testing purposes at this stage. 4.4.2. Building new images Early in the process of applying our changes, we realized that certain features that were available in the current GitHub main branch of DOMjudge were not yet available in the latest release. Among these features, there was the feedback message options, that contained all the changes related to the teammessage.txt file that we used for our implementation. This meant that the Docker containers that we had been using up to that point did not have this feature, as they are based on the latest available stable release of DOMjudge. The implementation of it has been discussed 38 Chapter 4. Integration of static and runtime analysis in DOMjudge Figure 4.5: DockerHub repositories in a GitHub issue with the developers before,11 and the feature was finally included on pull request #2016.12 Therefore, we had to generate a new image from GitHub’s source code to be able to use it. Fortunately, the DOMjudge developers maintain a DOMjudge-packaging repository on GitHub as part of the project. It contains all the requirements to create Docker images which can be used to run DOMjudge, provided as part of their support for contributors. We decided not to use it at first because we could simply deploy the published Docker images, and it worked just fine for us at first glance. By default, the provided scripts set everything up with maintained versions that do not contain the latest features that we need, being it the same one that is obtained during earlier Docker setups. To allow for the use of customized versions, we had to make some changes to the scripts and download the src code directly from the repository and run ‘make dist‘.13 An advantage that this approach also provided is that we could now specify what packages we want to include in the process of creating the image to be used, and not have to install them manually every single time. We removed them later for the final version, as they are no longer required. An important note to make is that the latest Docker version release has features that are incompatible with the build process, and we had to downgrade to Docker version 24.0.6. After all the changes were made, we successfully generated new images to be used for our testings. We uploaded them to a public Docker Hub repository in order to make it accessible to all the members. Apart from the team messages inclusion, this version comes with a more refined looking UI and additional features that we would not use for the development of the project, but are either way nice to have. 4.4.3. Automating the process At this stage, we decided that it would be very convenient to have an appropriate automated method to deploy the environment on all of our local machines without the hustle of doing it manually. The logic path to follow was the one of creating a Docker compose file [17]. The steps to carry this out involved the creation of a script that orchestrates 11https://github.com/DOMjudge/DOMjudge/issues/991 [9] 12https://github.com/DOMjudge/DOMjudge/pull/2016 13A makefile is a way of automating software building procedure and other complex tasks with dependencies. The dist rule in the generated Makefile can be used to generate a gzipped tar file and other flavors of archive for distribution. [10] [26] 4.4. Preparations and Setup 39 the process. The script executes the appropriate docker-compose commands on two compose files. The first one creates the MariaDB database and DOMServer containers, and the second one creates the one for the judgehost, and they are created in the mentioned order, as the judgehost depends on the DOMServer, which depends on the database. In the end, we obtain the same result but faster and in a simpler manner. Figure 4.6 displays the generated containers using the compose files. It successfully automates the container generation process. Figure 4.6: Containers view from Docker Desktop Chapter 5 Real use case scenario For testing and showcasing the performance of the modified DOMjudge, we prepared two examples that serve as a proof of concept. Firstly, a test problem and submission that contains a variety of fictitious errors to be detected during the evaluation process that will serve as a showcase of the analysis tools outputs. For the second example, we simulated a fictitious student submission that attempts to be as realistic as possible. 5.1. Showcase We have developed a minimal artificial problem that expects the following output: Correct solution! and a testcase.cpp file that will be used as the submission. This submission file will trigger several warnings that will be detected by the static analyzers and the sanitizers. For this purpose, we will indicate as a header of the test case that we want to perform a run with all the included features. This is the content for the test case submission: [...] // omitted lines void *p; int main() { int ways[3]; for (int i= 0; i < 3; i++) { ways[i] =i; } ways[2]=ways[2];//selfAssignment if (ways[2]== 2); 41 48 Chapter 5. Real use case scenario will still be able to know if there is something to improve in their codes. 5.2. Realistic Case Scenario For the realistic case scenario, we used a submission that attempts to be as close to reality as possible. To simulate real behavior, every iteration of a submission will apply a fix from the suggestions. The submission is attempting to solve a problem presented as follows: There is a celebration at a table in the shape of a ring where n guests can sit inside and another n guests outside (with n≤10,000). The sequence of guests inside and the sequence of guests outside are fixed, but it is still possible to decide how to align the two sequences. Each person has a level of enthusiasm (an integer whose absolute value is less than 106), and the enthusiasm of the celebration is the sum of the products of the enthusiasms of the people who are facing each other at the table. The problem consists of finding the maximum possible enthusiasm. The solution of the problem is this formula where v1and v2are the enthusiasm arrays for the inside and outside sequences of guests: max{ |v1|−1 X i=0 v1[i]·v2[i+k]|0≤k≤ |v1| − 1} Two test cases are included for the problem. The first one will be flagged with the header used to apply all the tools simultaneously. Since the output of a static analyzer is independent of the test case input, we will indicate for the second test case that we only want to run the instrumentation. This will avoid including the same errors and warnings twice for the case of the static analyzers. Let us submit first a faulty solution whose more relevant function is the following sumProduct: using tAnim =int; tAnim sumProduct(vector<tAnim>v1, vector<tAnim>v2, int offset) { int numSeats =v1.size(); tAnim total = 0; for (int i= 0; i <numSeats; ++i) total += v1[i] *v2[offset +i]; // Array out of bounds access,→ return total; } Once it is submitted, we get the following generated output: 5.2. Realistic Case Scenario 49 A heap overflow was detected, this is usually due to an out of bounds array access but can also be caused by repeated or big memory allocations using the malloc function or the new keyword. ,→ ,→ ,→ Error: signed integer overflow Error: signed integer overflow 50 Chapter 5. Real use case scenario A heap overflow was detected, this is usually due to an out of bounds array access but can also be caused by repeated or big memory allocations using the malloc function or the new keyword. ,→ ,→ ,→ containing the error: A heap overflow was detected, this is usually due to an out of bounds array access but can also be caused by repeated or big memory allocations using the malloc function or the new keyword. ,→ ,→ ,→ hinting at an array out of bounds access. This clue may help us find where the bug is. In this example, there is a missing modulo to never exceed the maximum number of available seats. After fixing it, we submit the code and obtain a new result. Message: Try avoiding operating between different types as it can cause unexpected behavior,→ Error: signed integer overflow Error: signed integer overflow In this second attempt, there is no longer an out-of-bounds access to the array, but we can still see the other same message and errors as in the previous attempt since we have not addressed them. No location for the errors are being shown yet. The same error appears twice since it is occurring at two different locations, but we do not know them yet. We will make another submission trying to fix the issues. Message: narrowing conversion from 'std::vector::size_type'(aka 'unsigned long') to signed type 'int'is implementation-defined, this is best avoided as it can lead to unexpected behavior ,→ ,→ ,→ Error: signed integer overflow Location of the error: Line: 15, Column: 18 Error: signed integer overflow Location of the error: Line: 15, Column: 9 Unfortunately, the problems were not solved, but we now have the location of the errors and a more detailed description message. Inspecting the “signed integer overflow” error, we can see that it is found at line: 5.2. Realistic Case Scenario 51 total += v1[i] *v2[(offset +i) %numSeats]; The reason behind this error trigger is that the value generated by the product is too large to fit inside the current 32 bit integer variable that is used to store it ((106)2>231). Execution is not stopped despite this. It is something that should be addressed, as it can lead to undefined behavior. Observing the returned message, we are determined to make some changes in order to achieve a better solution in the next submission. The error is caused because of the size of the type used for the alias declaration. using tAnim =int; The newly modified submission will fix it by specifying that we want to use 64-bit integers, greater than the 32-bit integer used before. using tAnim =int64_t; The generated team message is still shown even when the submission is evaluated as correct, as mentioned earlier. This will allow to be able to detect possible performance issues even when reaching a right solution that compute the correct result. With this in consideration, a new attempt is uploaded. Message: narrowing conversion from 'std::vector::size_type'(aka 'unsigned long') to signed type 'int'is implementation-defined, this is best avoided as it can lead to unexpected behavior ,→ ,→ ,→ Message: narrowing conversion from 'tAnim'(aka 'long') to signed type 'int'is implementation-defined, this is best avoided as it can lead to unexpected behavior ,→ ,→ We will attempt to change the code once more to try to eliminate the warnings and get the correct solution by changing the type of the variable sum used inside the function solvecase() from int to tAnim: vector<tAnim>inner(numSeats), outer(numSeats); This is the returned message for the submission: Message: narrowing conversion from 'std::vector::size_type'(aka 'unsigned long') to signed type 'int'is implementation-defined, this is best avoided as it can lead to unexpected behavior ,→ ,→ ,→ We did get an accepted verdict this time. Still, the warnings are displayed. It is common to have some despite writing proper code, as many different checks are made. With this test, we have tested the correct performance of the modified judge on a realistic student submission. Errors can sometimes be puzzling, especially when specialized language is used to describe them. In our approach, we have attempted to ease the readability of the warnings. Chapter 6 Conclusions and Future Work 6.1. Discussion and conclusions In this thesis we have made a study on two different static analyzers (Clang-tidy and Cppcheck), we have analyzed the outputs these tools gave us in a dataset of more than 4000 submissions. After the analysis, we have concluded which checks were more relevant. Then, we followed a similar process to understand instrumentation, we studied ASan and UBSan. While those studies were being made, we also started modifying the DOMjudge platform, in order to develop a way to communicate to the student the feedback we were creating. Finally, as we finished all those tasks, we developed a didactic, personal feedback based on the diagnostics issued for the student submissions. This feedback is shown to the student via teammessage (a functionality of DOMjudge) when they submit their code. After fixing Clang-Tidy, Cppcheck, ASan, and UBSan as target tools, we analyzed their diagnostics. There are no known studies about these tools on student submissions. So in this thesis we have made an exhaustive analysis on all the diagnostics that could be raised in student submissions and made clear which diagnostics are we are actually going to communicate, excluding those with little to no relevance for a didactic and useful feedback. We then integrate the tools into DOMjudge. To make it, we have requested aid from the developers of the platform in order to fix various issues that arose during the pertinent modifications of the platform (for example to include an “outdated” messaging system that the platform provided “teammessage”) and changes to the assessment process of the online judge, specifically, the compare and run scripts in order to run the static and dynamic analyzers of code on the submission. We also needed to make some changes within the DOMjudge PHP code and the HTML templates. This process concluded by giving relevant feedback to the students about their code, and aid instructors on the assessment of assignments (it seems important to remark that we give the instructor 7 different types of modes in which the online judge will run or not the static and dynamic analyzers). Our developments provide an example to other teaching institutions in order to implement feedback based on code analysis when needed on an online judge. With the extension made on DOM- 53 54 Chapter 6. Conclusions and Future Work judge, we detect and communicate most errors regarding memory and undefined behavior, and through linting and static analysis we analyze other properties of the code that are not detected by ASan or UBSan. 6.2. Future work During the development of this project, we have come up with ideas and features that we would have been delighted to implement, but exceeded the focus of the project or could not include due to time restrictions. Firstly, we would have loved to make the features available to other languages outside of C++. The main reason behind not doing this was that C++ is the main language used in our laboratories for the different subjects, and adding support to unused languages was not a priority. To do this, the judge should be able to identify the language from within the run script to know what static analyzers and instrumentation to run. Another feature that caught our interest was including the information of whether past submissions had been accepted or rejected by the judge and the reason for it. This would have allowed us to develop more reactive messages and perform a more complex message generation. In the end, we did not include this feature due to time restrictions. As it was discussed in the static analyzers conclusions, the analysis done on students submissions doesn’t differ from problem to problem, running an analysis specific to the problem and providing the maintainer of the online judge an interface to do this easily, would solve this limitation. In [3], the authors propose the CAC++ library, construct tailored static analysis programs for C/C++ assignments. By integrating it, we could be able to detect the targeted logic errors. We also thought about implementing the run options inside the test cases themselves. While functional, it is not the most user-friendly approach. An ideal solution would involve adding options and buttons in the user interface to select and activate these features. It would require work that falls outside the scope of this project, but would be positive to have. Lastly, we would like to mention that our tutor’s and other professors from our university have planned to use the DOMjudge integration developed in this thesis on some subjects in the computer science school at UCM for next year. Indeed, a teaching innovation project (number 71 of the 2024/25 call) has been awarded to a group of people including us. To improve this project it would be useful to have even more student submissions to see in more detail the most common errors among students. It will be useful to also consider different kinds of problems and subjects (for example, we coded in purpose a division by zero to see if a check was raised, but we did not find it raised in any of the +4000 submissions available) With this thesis we have created a path to implement many other improvements for the feedback given by DOMjudge. This project is scalable and modular, so we expect that in the close future we can see this thesis as the basis for a better automated code assessment at the Universidad Complutense de Madrid. Chapter 7 Personal Contributions In this section, we will specify the job performed by each of the team members inside this project. 7.1. Rodrigo Burgos Sosa During the initial phase of the project, I explored some of the different static analyzers that existed and the ones that could be more beneficial for our purpose. When looking at what each of them had to offer and decided to go for Clang and Cppcheck, I read through the different documentations provided and made sure to understand how they worked and the installation process. SonarQube and CodeChecker were other of the options that were considered, the second one for its Cross Translation Unit feature that we ended up deciding not to include. Many of the arguments added to the command lines of the static analyzers were chosen thanks to this process. Through my investigation, I also realized that Clang-Tidy offered more value to us than Clang by itself, as it ran the same checks that the latter, in addition to some of its own. It, too, was simpler to set up than Clang, and we decided to use Clang-Tidy for these reasons. To perform the initial execution of the analyzers with the student submissions, I developed the scripts to run them on all the submissions and obtain the parseable files in collaboration with Luis and Juan. From this point onwards, I dedicated my time to the judge modifications. Firstly, I read through their documentation to understand how DOMjudge worked and the available features. I will use this space to express my gratitude personally to all the DOMjudge developers for maintaining such a complete documentation. Speaking of which, I was in charge of the communication with the developers, as the information they provided affected directly my part of the work. To do so, I subscribed to the development mailing list and expressed my doubts through there. The process is very simple, one has to subscribe (done to counter spam) and once the process is completed, I could send messages to the mailing list. Communication with the team was key in order to overcome some difficulties for our implementation. Jaap Eldering and Michael Vasseur, two of the main developers for the judge, answered everything we asked and guided some of our thoughts. I also explored everything 55 56 Chapter 7. Personal Contributions that the project had to offer, which is how we found out about all the repositories specially aimed at other developers attempting to make their contribution to the judge. Thanks to these repositories, I was able to build the new images that were used during the implementation process. Despite how well the project is maintained, I still ran into some issues when using this resources to set everything up [42, 39]. For instance, I had to make sure that I enabled plugins to run when executing compose as root1, since at a given point, the option for plugins to run by default in Compose was disabled 2. The Symfony plugin was affected by this, for instance. Also, some changes had to be made to some scripts to add features or options that are not the default behavior, as mentioned elsewhere in this thesis. A very important fix that had to be made was the fact that the web interface formatting at a certain point was not formatting properly and the styling was not loading, not only making the web page visually worse, but also making the whole user experience far less enjoyable and even removing some interactions, like the ability of adding problems to a contest, since certain buttons did not load. A message was sent to the team and this was a known issue that some users had reported already and are working on. They did suggest a possible fix, which should have been part of the process from the beginning anyway, which was running the Make dist on the code. This fortunately solved a problem that could have otherwise greatly detracted from the final product. All of this required a process of investigation and troubleshooting to find the issues and the solutions; many of them were found in GitHub and Stack Overflow threads and discussions, and some others by diving into specific documentations. At the end, more time was spent troubleshooting and fixing issues that I could have anticipated. Once the images were created correctly, I developed the compose files that were used later by the team to test out the final changes. But, honestly, it was a feature that was mostly used by myself, so more than anything, it was a quality of life improvement. Either way, it allows anyone to easily deploy our version of DOMjudge with ease on their machines. In order to use Docker on my machine, I downloaded Windows Subsystem for Linux 2 (WSL2) 3since I personally use Windows on it. This allowed the whole setup to be easier and more convenient to use. It required a bit of setting up in order to make it work in synchronization with Docker. By far, the part that consumed most of my time was understanding how to make the appropriate changes inside the judge. Most of my findings have already been exposed throughout this thesis, but many of the difficulties have not been explained. One of the most important milestones was the process of retrieving the number of submissions for a given problem by a student in order to use it to generate the feedback message. The process involved a lot of work to understand and make correctly. Firstly, I had to research how the API worked and where I could 1https://github.com/api-platform/api-platform/issues/2610 2https://github.com/composer/composer/issues/11839 [1] 3Windows Subsystem for Linux (WSL) is a feature of Windows that allows to run a Linux environment on your Windows machine, without the need for a separate virtual machine or dual booting https://learn.microsoft.com/en-us/windows/wsl/about https://learn. microsoft.com/en-us/windows/wsl/tutorials/wsl-containers [24]. 7.2. Juan Trillo Carreras 57 find the required information, to then identify the appropriate place from where the information should be requested, landing luckily inside the judgedaemon.main.php. Thanks to the DOMjudge developers, we understood that modifying the JudgeTask entity would be very beneficial, but the change was not as straight forwards as initially thought. A database migration was, of course, required to apply the change, and this required to understand at a surface level how to deal with Symfony and databases. Even with this, the migration process still ran into issues because I had to specify the DATABASE_URL environment variable inside the .env.local file. Many thanks to the threads that helped me solve the problems throughout this process. Finding the most appropriate method to run the static analyzers and instrumentation was not an easy task either, and multiple options and configurations were tried in order to land on the final version. The process was in constant evolution, as a new method would lead the way into attempting to perform the same action but in a simpler or better implemented manner. Figuring out what specific changes had on the evaluation process was certainly doubt-inducing, and their effect would dictate the decisions taken. At some point, compilation of the code could be directly performed with instrumentation in the compile script, which meant that code had to be compiled only once per test case (if necessary), but DOMjudge did not tolerate working with two different compilation results if a test case performed compilation with instrumentation and another one did not, so we had to scrap the idea. In the end, the solution found was a far less complicated workaround. Parts for the solution also involved modifying PHP and HTML code, which I was not familiar with before beginning this project. Many of the changes were made by observing sections of the code and trying to replicate them to achieve my goals. Finally, I was in charge of writing in this thesis everything that had to do with the modifications made to the judge, apart of the common sections to the whole team (introduction, conclusions, ...), which were written by the three of us. 7.2. Juan Trillo Carreras During the first phase of the project, I coordinated the rest of the participant’s tasks, while Rodrigo explored superficially some of the different static analyzers and Luis the sanitizers, I studied thoroughly Cppcheck as it was the most complete and the one I felt was going to be more helpful for the feedback to the students when improving the answers of DOMjudge. After our first exploration, I started coding together with Rodrigo and Luis the initial bash to get different submissions to be examined by the different analyzers chosen. I made the final modifications of the script. After completing the script in bash we decided to make different Python scripts to examine the “raw” output of the analyzers. Through this second phase we had various changes in how to read the output for the tools as they had different options for the outputs. For example, at first I wrote one script for taking the SARIF output of Clang, but at the end we decided to take the YAML output. All the Python scripts were going to be ran by the initial bash script, so I had to make more changes to the initial script as I progressed with the other scripts. I was in charge of the main script used for Clang and Cppcheck. At first, we united all the 64 BIBLIOGRAPHY [15] Anthony Heddings. What is chroot on Linux and how do you use it?, 2020. url:https://www.howtogeek.com/devops/what-is-chroot-on-linux- and-how-do-you-use-it/. [16] Colin Hughes. Project Euler, 2001. url:https://projecteuler.net. [17] Docker Inc. Docker Compose overview | Docker docs, 2013. url:https:// docs.docker.com/compose/. [18] Docker Inc. Docker docs, 2013. url:https://docs.docker.com/. [19] Linux kernel development community. Control groups version 1, The Linux Kernel documentation, 2024. url:https://www.kernel.org/doc/html/ latest/admin-guide/cgroup-v1/index.html. [20] Rüdiger Landmann, Jack Reed, et al. The GRUB loader. In Red Hat Enterprise Linux 5: Installation Guide. 2024. Chapter 9. url:https://access. redhat.com/documentation/en-us/red_hat_enterprise_linux/5/html/ installation_guide/ch-grub. [21] Kaibo Liu, Yudong Han, Jie M. Zhang, Zhenpeng Chen, Federica Sarro, Mark Harman, Gang Huang, and Yun Ma. Who judges the judge: an empirical study on online judge tests. In René Just and Gordon Fraser, editors, Proceedings of the 32nd ACM SIGSOFT International Symposium on Software Testing and Analysis, ISSTA 2023, Seattle, WA, USA, July 17-21, 2023, pages 334–346. ACM, 2023. [22] Anaga Mani, Divya Venkataramani, Jordi Petit Silvestre, and Salvador Roura Ferret. Better feedback for educational online judges. In Proceedings of the 6th International Conference on Computer Supported Education, Volume 2: Barcelona, Spain, 1-3 April, 2014, pages 176–183. SciTePress, 2014. [23] Daniel Marjamäki. Cppcheck, 2007. url:https://sourceforge.net/p/ cppcheck/wiki/ListOfChecks/. [24] Microsoft. WSL documentation, 2016. url:https://learn.microsoft.com/ en-us/windows/wsl/. [25] IOI organization. International Olympiad in Informatics, 1989. url:https: //ioinformatics.org. [26] Sachin Patil. What is a makefile and how does it work?, 2018. url:https: //opensource.com/article/18/8/what-how-makefile. [27] Jordi Petit and Salvador Roura. Jutge.org, 2006. url:https://jutge.org. [28] Henry Gordon Rice. Classes of recursively enumerable sets and their decision problems. Transactions of the American Mathematical Society, 74(2):358–366, 1953. [29] Symfony SAS. Symfony. High performance PHP framework for web development, 2005. url:https://symfony.com/. [30] Carlos Solar Sastre. Desarrollo de una Plataforma Orientada al Refuerzo en la Evaluación del Nivel de Programación. Bachelor’s thesis, Universidad Politécnica de Madrid, 2020. url:https://oa.upm.es/63124/. BIBLIOGRAPHY 65 [31] UNICOM Systems. Purify, 1992. url:https://www.unicomsi.com/products/ purifyplus/. [32] UNICOM systems. Quantify, 1992. url:https : / / www . unicomsi . com / products/quantify/. [33] Clang Team. AddressSanitizer — Clang 19.0.0git documentation, 2012. url: https://clang.llvm.org/docs/AddressSanitizer.html (visited on 2024). [34] Clang Team. Clang-Tidy checks, 2024. url:https : / /clang . llvm. org / extra/clang-tidy/checks/list.html. [35] Clang Team. UndefinedBehaviorSanitizer — Clang 19.0.0git documentation, 2012. url:https://clang.llvm.org/docs/UndefinedBehaviorSanitizer. html#ubsan-checks (visited on 2024). [36] DOMjudge team. Domjudge manual, 2004. url:https://www.DOMjudge. org/docs/manual/8.2/index.html. Manual for the DOMjudge. [37] ICPC team. Contest API, 2010. url:https://ccs-specs.icpc.io/draft/ contest_api#introduction. Contest API documentation. [38] Tpoint Tech. Linux arguments, 2011. url:https://www.javatpoint.com/ linux-arguments. [39] user3001829. How to copy files from host to Docker container?, 2014. url: https://stackoverflow.com/questions/22907231/how-to-copy-files- from-host-to-docker-container. [40] Szymon Wasik, Maciej Antczak, Jan Badura, Artur Laskowski, and Tomasz Sternal. A survey on online judge systems and their applications. ACM Comput. Surv., 51(1):3:1–3:34, 2018. eprint: https:/ /arxiv. org /abs/ 1710. 05913. [41] Alex Williams. What is Symfony?, 2022. url:https : / / builtin . com / software-engineering-perspectives/symfony. [42] Catch Zeng. Tool - Docker build not showing any output from commands (Dockerfile RUN), 2016. url:https://makeoptim.com/en/tool/dockerbuild-not-output/. Appendix A Offline analysis details A.1. Most relevant Clang-Tidy diagnostics In Table A.1 we show the number of occurrences of each diagnostic within all of the submissions, shown in the second column. But, in order to avoid any kinds of bias related to diagnostics appearing multiple times within a team or a problem we added two other columns. The third column counts the number of team’s submissions for a problem which contained the diagnostic, and the fourth column contains the number of problems which have submissions containing the diagnostic. The last column displays the number of transitions from not accepted submissions to accepted ones when a diagnostic is fixed. The table is ordered by transitions to AC then by total occurences. It contains the first 40 after removing checks concerning a specific project, security and concurrency, some specific checks that are not very relevant are also removed, they are related with very opinionated style requirements that students do not follow. Table A.1: performance-avoid-endl 564 263 48 18 misc-no-recursion 407 196 25 11 readability-implicit-bool-conversion 156 69 19 8 bugprone-exception-escape 702 322 26 7 bugprone-narrowing-conversions 481 241 38 7 cppcoreguidelines-pro-type-member- init 277 134 29 7 google-explicit-constructor 204 118 15 7 bugprone-integer-division 21 11 1 6 modernize-use-nodiscard 314 159 21 5 Name Submission Team Problem AC Trans Continued on next page 67 68 Appendix A. Offline analysis details Table A.1: (Continued) readability-make-member-function- const 134 85 14 5 cppcoreguidelines-prefer-member- initializer 44 30 8 5 modernize-loop-convert 184 94 25 4 modernize-use-transparent-functors 123 76 15 4 readability-simplify-boolean-expr 62 40 15 4 readability-function-cognitive- complexity 52 16 9 4 bugprone-easily-swappable-parameters 285 172 34 3 google-runtime-int 218 87 24 3 performance-for-range-copy 117 64 11 3 cppcoreguidelines-avoid-const-or-ref- data-members 111 70 11 3 clang-diagnostic-empty-body 62 27 20 3 clang-analyzer-deadcode.DeadStores 57 32 15 3 bugprone-branch-clone 56 25 12 3 modernize-return-braced-init-list 25 9 4 3 cppcoreguidelines-use-default- member-init 255 148 17 2 bugprone-reserved-identifier 128 64 6 2 misc-non-private-member-variables-in- classes 107 52 15 2 performance-unnecessary-value-param 78 56 21 2 modernize-use-using 67 26 12 2 hicpp-use-emplace 49 32 16 2 misc-unused-parameters 30 20 16 2 clang-diagnostic-parentheses-equality 5 2 1 2 clang-diagnostic-error 91 57 18 1 clang-diagnostic-return-type 60 41 8 1 cppcoreguidelines-non-private- member-variables-in-classes 48 34 10 1 bugprone-suspicious-semicolon 38 16 11 1 cppcoreguidelines-macro-usage 36 17 11 1 Name Submission Team Problem AC Trans Continued on next page A.2. Cppcheck error list 69 Table A.1: (Continued) readability-misleading-indentation 33 16 13 1 modernize-pass-by-value 24 16 9 1 modernize-macro-to-enum 21 11 11 1 Name Submission Team Problem AC Trans A.2. Cppcheck error list Here is the list of the most relevant checks of Cppcheck found and the reasons of why we chose them: missingReturn (error) •From 46 occurrences WA : 6.52%’, CE : 17.39%, RTE : 4.35%, TLE : 2.17%, AC : 69.57%.As the DOMjudge does only rely on output to state an AC, we can see how this result is happening. However this is a very poor coding practice and could cause problems. •"Found an exit path from function with non-void return type that has missing return statement" •If not handled will probably cause errors. •Check should be communicated although it may not cause any problems, it aids the student in a didactic way. uninitStructMember (error) •From 28 occurrences WA : 57.14%’, CE : 21.43%, RTE : 10.71%, AC : 10.71%. Probably an unintended error. •"Uninitialized struct member: ****" •Part of the struct is not given type / initialized by the programmer but it was defined by themselves this is quite suspicious and should be communicated. unreadVariable (style) •From 300 occurrences WA : 36.12%’, CE : 7.02%, RTE : 11.71%, TLE : 13.04%, AC : 32.11%. •"Variable ’**’ is assigned a value that is never used." •Not reaching a variable (which means that a variable was not read during execution) is the consequence of: part of the code is unreachable, there is an infinite loop (TimeLimitException), the program cannot be compiled completely (CompileError) or a mix of those reasons. •Should be communicated in case of TLE , CE and WA. shadowFunction/shadowVariable/shadowArgument (style) 70 Appendix A. Offline analysis details •Except from shadowFunction that has just a 13.33% of AC the rest have a relatively high acceptance rate (around 40%) in comparison. •"Local variable ’**’ shadows outer function/Variable/Argument" •The programmer may be inadvertently using a name already used by the program thinking that they are required to be connected when they are not. •Should be communicated in case of not being AC. knownConditionTrueFalse (style) •From 52 occurrences WA : 28.85%’, CE : 9.62%, RTE : 23.08%, TLE : 32.69%, AC : 5.77%. •"Condition ’arbol.empty()’ is always false" •Almost never arises when the program is AC. Although this might be a conscious decision of the student, this can lead to various problems. •Should be communicated for maybe aiding the student in a didactic way. redundantCondition (style) •From just 4: 3 are RTE , and just 1 is TLE . •"Redundant condition: j==0. ’j==0 || (j==0 AND i==-1)’ is equivalent to ’j==0’" •Tightly related to RTE and TLE (caused mainly by unconscious infinite loops). multiCondition (style) •2 occurrences both of them RTE . •"Expression is always true because ’else if’ condition is opposite to previous condition at line 56." •Tightly related to RTE. duplicateExpression (style) •From 17 occurrences WA : 29.41%’, CE : 11.76%, RTE : 5.88%, TLE : 52.94%, AC :0% •"Same expression on both sides of ’>’." •Seems highly related to TLE (Infinite loops with while conditions) . duplicateBreak (style) •As one could imagine this check happens very unfrequently in our case we have just seen one case which was actually accepted. •"Consecutive return, break, continue, goto or throw statements are unnecessary." A.2. Cppcheck error list 71 •This is a bad coding practice. •Check should be communicated although it may not cause any problems, it aids the student in a didactic way. noConstructor (style) •With just 2 occurrences, one was TLE and the other AC. •""The class ’Supermercado’ does not declare a constructor although it has private member variables which likely require initialization." •Could cause problems (in our dataset it lead to errors). •Should be communicated in any case different from AC. unreachableCode (style) •Surprisingly this just happens once, and its AC, after further investigation, we noticed that this was because it was related to the duplicateBreak error. •"Statements following ’return’ will never be executed." •Could cause problems as it can be highly associated with infinite loops or conditions that will never actually be met because of the code. •Should be communicated in any case different from AC. knownEmptyContainer (style) •Just one occurrence, an OLE verdict, as the example shows, it was outputting an empty result with probably a fixed output format, and as it was iterating over it, it made it exceed the output limit. •"Iterating over container ’sol’ that is always empty." •Will lead to problems, highly related to OLE. •Should be communicated in any case different from AC. clarifyCondition (style) •Just one occurrence in the dataset, surprisingly less than we originally theorized however it is relevant and the verdict was WA. •"Boolean result is used in bitwise operation. Clarify expression with parentheses." •Will cause problems, highly related to WA. •Should be communicated in any case different from AC. uninitvar (warning) •From 14 occurrences WA : 28.57%’, RTE : 28.57%, TLE : 19.05%, AC : 23.81% 72 Appendix A. Offline analysis details •"Uninitialized variable: ***.h" •Not initialized variable (it is a warning because as you can see is mainly associated with header files wrongly interpreted). selfAssignment (warning) •Just 9 occurrences all of them WA, as expected, this is not a common error but its almost always "fatal" for the correctness of the answer. •"Redundant assignment of ’maneras[y]’ to itself." •Highly associated with WA. negativeContainerIndex (warning) •Just 6 occurrences, 2 of them caused an RTE which is normal as if it actually gives a negative cointainer index it will result in a run-time exception. •"Either the condition ’adyacentes[i]!=anterior’ is redundant, otherwise there is negative array index -1." •Highly associated with RTE, might cause runtime exceptions. containerOutOfBounds (warning) •WA : 4.76%’, CE : 23.812%, RTE : 66.67%, AC : 4.76%. These results makes sense, remember we are treating with static analysis so this error arises when a variable tries to access a part of a variable which can be empty or out of bounds, depending on the actual value of both variables, this can lead to different accesses resulting majorly in RTE. •"Either the condition ’****[0].empty()’ is redundant or expression ’****[0].front()’ cause access out of bounds." •Highly associated with RTE, might cause runtime exceptions. identicalInnerCondition (warning) •Just one occurrence, derived in an AC verdict, its definitely not an intended error so it must be notified. •""Identical inner ’if’ condition is always true." •Probably not intended. •Check should be communicated although it may not cause any problems, it aids the student. constStatement (warning) •From 7 occurrences WA : 14.29%’, CE : 28.57%, RTE : 28.57%, TLE : 14.29%, AC : 14.29%.It depends on the case. •Case 1 A.2. Cppcheck error list 73 ◦"Redundant code: Found a statement that begins with bool constant." ◦Highly associated with WA ◦Should be communicated as it can cause problems. •Case 2 ◦"Redundant code: Found unused array access." ◦Unused variable ◦Not relevant for feedback. Before going any further, now we are going to analyze performance errors, these imply always a bad/poor coding practice which means that they might not imply a judge verdict, however although not useful for the student to correct their answer, this kind of errors are very useful for them to integrate good coding practices to their codes. passedByValue (performance) •From 94 occurrences WA : 17.58%’, CE : 3.3%, RTE : 17.78%, TLE : 28.57%, AC : 30.77%. Just a poor coding practice, could deliver any kind of verdict, but it not the main reason for any of them. •"Function parameter ’tallaNecesitamos’ should be passed by const reference." •Poor coding practice. •Check should be communicated although it may not cause any problems, it aids the student in a didactic way. stlFindInsert (performance) •From 22 occurrences WA : 10%’, CE : 5%, RTE : 5%, TLE :5%, AC : 75%. Poor coding practice, does not imply any verdict. However it could be corrected. •"Searching before insertion is not necessary. Instead of ’personas[]=indPersona’ consider using .tryemplace •Poor coding practice. •Check should be communicated although it may not cause any problems, it aids the student in a didactic way. iterateByValue (performance) •From 8 occurrences WA : 14.29%’, CE : 28.57%, TLE : 28.57%, AC : 28.57%. Poor coding practice, does not imply any verdict. However it could be corrected. •"Range variable ’cancion’ should be declared as const reference." 80 Appendix B. Instructions for Docker setup docker run -it --privileged -v /sys/fs/cgroup:/sys/fs/cgroup:ro --name judgehost-0 --link domserver:domserver --hostname judgedaemon-0 -e DAEMON\_ID=0 -e JUDGEDAEMON\_PASSWORD=<judgehost password> domjudge/judgehost:latest ,→ ,→ ,→ ,→ Where <judgehost password> must contain the value retrieved earlier. This can be run multiple times to create as many instances of judgehost as necessary. The name and hostname must be changed to allow for this for each instance.