Merge pull request #21928 from fiigii/fixMulx
[platform/upstream/coreclr.git] / netci.groovy
1 // Import the utility functionality.
2
3 import jobs.generation.*
4
5 // The input project name (e.g. dotnet/coreclr)
6 def project = GithubProject
7 // The input branch name (e.g. master)
8 def branch = GithubBranchName
9 def projectFolder = Utilities.getFolderName(project) + '/' + Utilities.getFolderName(branch)
10
11 // Create a folder for JIT stress jobs and associated folder views
12 folder('jitstress')
13 Utilities.addStandardFolderView(this, 'jitstress', project)
14
15 // Create a folder for testing via illink
16 folder('illink')
17 Utilities.addStandardFolderView(this, 'illink', project)
18
19 def static getOSGroup(def os) {
20     def osGroupMap = ['Ubuntu'      : 'Linux',
21                       'Ubuntu16.04' : 'Linux',
22                       'Ubuntu16.10' : 'Linux',
23                       'RHEL7.2'     : 'Linux',
24                       'Debian8.4'   : 'Linux',
25                       'Fedora24'    : 'Linux',
26                       'CentOS7.1'   : 'Linux',
27                       'Tizen'       : 'Linux',
28                       'OSX10.12'    : 'OSX',
29                       'Windows_NT'  : 'Windows_NT']
30     def osGroup = osGroupMap.get(os, null)
31     assert osGroup != null : "Could not find os group for ${os}"
32     return osGroupMap[os]
33 }
34
35 // We use this class (vs variables) so that the static functions can access data here.
36 class Constants {
37
38     // We have very limited Windows ARM64 hardware (used for ARM/ARM64 testing) and Linux/arm32 and Linux/arm64 hardware.
39     // So only allow certain branches to use it.
40     def static LimitedHardwareBranches = [
41                'master']
42
43     // Innerloop build OS's
44     // The Windows_NT_BuildOnly OS is a way to speed up the Non-Windows builds by avoiding
45     // test execution in the build flow runs.  It generates the exact same build
46     // as Windows_NT but without running the tests.
47     def static osList = [
48                'Ubuntu',
49                'Debian8.4',
50                'OSX10.12',
51                'Windows_NT',
52                'Windows_NT_BuildOnly',
53                'CentOS7.1',
54                'RHEL7.2',
55                'Ubuntu16.04',
56                'Ubuntu16.10',
57                'Fedora24',
58                'Tizen']
59
60     def static crossList = [
61                'Ubuntu',
62                'Debian8.4',
63                'OSX10.12',
64                'Windows_NT',
65                'CentOS7.1',
66                'RHEL7.2']
67
68     // This is a set of JIT stress modes combined with the set of variables that
69     // need to be set to actually enable that stress mode.  The key of the map is the stress mode and
70     // the values are the environment variables
71     def static jitStressModeScenarios = [
72                'minopts'                        : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JITMinOpts' : '1'],
73                'tieredcompilation'              : ['COMPlus_TieredCompilation' : '1'], // this can be removed once tiered compilation is on by default
74                'no_tiered_compilation'          : ['COMPlus_TieredCompilation' : '0'],
75                'no_tiered_compilation_innerloop': ['COMPlus_TieredCompilation' : '0'],
76                'forcerelocs'                    : ['COMPlus_TieredCompilation' : '0', 'COMPlus_ForceRelocs' : '1'],
77                'jitstress1'                     : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '1'],
78                'jitstress2'                     : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2'],
79                'jitstress1_tiered'              : ['COMPlus_TieredCompilation' : '1', 'COMPlus_JitStress' : '1'],
80                'jitstress2_tiered'              : ['COMPlus_TieredCompilation' : '1', 'COMPlus_JitStress' : '2'],
81                'jitstressregs1'                 : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '1'],
82                'jitstressregs2'                 : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '2'],
83                'jitstressregs3'                 : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '3'],
84                'jitstressregs4'                 : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '4'],
85                'jitstressregs8'                 : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '8'],
86                'jitstressregs0x10'              : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '0x10'],
87                'jitstressregs0x80'              : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '0x80'],
88                'jitstressregs0x1000'            : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '0x1000'],
89                'jitstress2_jitstressregs1'      : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2', 'COMPlus_JitStressRegs' : '1'],
90                'jitstress2_jitstressregs2'      : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2', 'COMPlus_JitStressRegs' : '2'],
91                'jitstress2_jitstressregs3'      : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2', 'COMPlus_JitStressRegs' : '3'],
92                'jitstress2_jitstressregs4'      : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2', 'COMPlus_JitStressRegs' : '4'],
93                'jitstress2_jitstressregs8'      : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2', 'COMPlus_JitStressRegs' : '8'],
94                'jitstress2_jitstressregs0x10'   : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2', 'COMPlus_JitStressRegs' : '0x10'],
95                'jitstress2_jitstressregs0x80'   : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2', 'COMPlus_JitStressRegs' : '0x80'],
96                'jitstress2_jitstressregs0x1000' : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2', 'COMPlus_JitStressRegs' : '0x1000'],
97                'tailcallstress'                 : ['COMPlus_TieredCompilation' : '0', 'COMPlus_TailcallStress' : '1'],
98                'jitsse2only'                    : ['COMPlus_TieredCompilation' : '0', 'COMPlus_EnableAVX' : '0', 'COMPlus_EnableSSE3_4' : '0'],
99                'jitnosimd'                      : ['COMPlus_TieredCompilation' : '0', 'COMPlus_FeatureSIMD' : '0'],
100                'jitincompletehwintrinsic'       : ['COMPlus_TieredCompilation' : '0', 'COMPlus_EnableIncompleteISAClass' : '1'],
101                'jitx86hwintrinsicnoavx'         : ['COMPlus_TieredCompilation' : '0', 'COMPlus_EnableIncompleteISAClass' : '1', 'COMPlus_EnableAVX' : '0'], // testing the legacy SSE encoding
102                'jitx86hwintrinsicnoavx2'        : ['COMPlus_TieredCompilation' : '0', 'COMPlus_EnableIncompleteISAClass' : '1', 'COMPlus_EnableAVX2' : '0'], // testing SNB/IVB
103                'jitx86hwintrinsicnosimd'        : ['COMPlus_TieredCompilation' : '0', 'COMPlus_EnableIncompleteISAClass' : '1', 'COMPlus_FeatureSIMD' : '0'], // match "jitnosimd", may need to remove after decoupling HW intrinsic from FeatureSIMD
104                'jitnox86hwintrinsic'            : ['COMPlus_TieredCompilation' : '0', 'COMPlus_EnableIncompleteISAClass' : '1', 'COMPlus_EnableSSE' : '0' , 'COMPlus_EnableSSE2' : '0' , 'COMPlus_EnableSSE3' : '0' , 'COMPlus_EnableSSSE3' : '0' , 'COMPlus_EnableSSE41' : '0' , 'COMPlus_EnableSSE42' : '0' , 'COMPlus_EnableAVX' : '0' , 'COMPlus_EnableAVX2' : '0' , 'COMPlus_EnableAES' : '0' , 'COMPlus_EnableBMI1' : '0' , 'COMPlus_EnableBMI2' : '0' , 'COMPlus_EnableFMA' : '0' , 'COMPlus_EnableLZCNT' : '0' , 'COMPlus_EnablePCLMULQDQ' : '0' , 'COMPlus_EnablePOPCNT' : '0'],
105                'corefx_baseline'                : ['COMPlus_TieredCompilation' : '0'], // corefx baseline
106                'corefx_minopts'                 : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JITMinOpts' : '1'],
107                'corefx_tieredcompilation'       : ['COMPlus_TieredCompilation' : '1'],  // this can be removed once tiered compilation is on by default
108                'corefx_jitstress1'              : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '1'],
109                'corefx_jitstress2'              : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStress' : '2'],
110                'corefx_jitstressregs1'          : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '1'],
111                'corefx_jitstressregs2'          : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '2'],
112                'corefx_jitstressregs3'          : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '3'],
113                'corefx_jitstressregs4'          : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '4'],
114                'corefx_jitstressregs8'          : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '8'],
115                'corefx_jitstressregs0x10'       : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '0x10'],
116                'corefx_jitstressregs0x80'       : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '0x80'],
117                'corefx_jitstressregs0x1000'     : ['COMPlus_TieredCompilation' : '0', 'COMPlus_JitStressRegs' : '0x1000'],
118                'gcstress0x3'                    : ['COMPlus_TieredCompilation' : '0', 'COMPlus_GCStress' : '0x3'],
119                'gcstress0xc'                    : ['COMPlus_TieredCompilation' : '0', 'COMPlus_GCStress' : '0xC'],
120                'zapdisable'                     : ['COMPlus_TieredCompilation' : '0', 'COMPlus_ZapDisable' : '1', 'COMPlus_ReadyToRun' : '0'],
121                'heapverify1'                    : ['COMPlus_TieredCompilation' : '0', 'COMPlus_HeapVerify' : '1'],
122                'gcstress0xc_zapdisable'             : ['COMPlus_TieredCompilation' : '0', 'COMPlus_GCStress' : '0xC', 'COMPlus_ZapDisable' : '1', 'COMPlus_ReadyToRun' : '0'],
123                'gcstress0xc_zapdisable_jitstress2'  : ['COMPlus_TieredCompilation' : '0', 'COMPlus_GCStress' : '0xC', 'COMPlus_ZapDisable' : '1', 'COMPlus_ReadyToRun' : '0', 'COMPlus_JitStress'  : '2'],
124                'gcstress0xc_zapdisable_heapverify1' : ['COMPlus_TieredCompilation' : '0', 'COMPlus_GCStress' : '0xC', 'COMPlus_ZapDisable' : '1', 'COMPlus_ReadyToRun' : '0', 'COMPlus_HeapVerify' : '1'],
125                'gcstress0xc_jitstress1'             : ['COMPlus_TieredCompilation' : '0', 'COMPlus_GCStress' : '0xC', 'COMPlus_JitStress'  : '1'],
126                'gcstress0xc_jitstress2'             : ['COMPlus_TieredCompilation' : '0', 'COMPlus_GCStress' : '0xC', 'COMPlus_JitStress'  : '2'],
127                'gcstress0xc_minopts_heapverify1'    : ['COMPlus_TieredCompilation' : '0', 'COMPlus_GCStress' : '0xC', 'COMPlus_JITMinOpts' : '1', 'COMPlus_HeapVerify' : '1']
128     ]
129
130     // This is a set of ReadyToRun stress scenarios
131     def static r2rStressScenarios = [
132                'r2r_jitstress1'             : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStress": "1"],
133                'r2r_jitstress2'             : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStress": "2"],
134                'r2r_jitstress1_tiered'      : ['COMPlus_TieredCompilation' : '1', "COMPlus_JitStress": "1"],
135                'r2r_jitstress2_tiered'      : ['COMPlus_TieredCompilation' : '1', "COMPlus_JitStress": "2"],
136                'r2r_jitstressregs1'         : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStressRegs": "1"],
137                'r2r_jitstressregs2'         : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStressRegs": "2"],
138                'r2r_jitstressregs3'         : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStressRegs": "3"],
139                'r2r_jitstressregs4'         : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStressRegs": "4"],
140                'r2r_jitstressregs8'         : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStressRegs": "8"],
141                'r2r_jitstressregs0x10'      : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStressRegs": "0x10"],
142                'r2r_jitstressregs0x80'      : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStressRegs": "0x80"],
143                'r2r_jitstressregs0x1000'    : ['COMPlus_TieredCompilation' : '0', "COMPlus_JitStressRegs": "0x1000"],
144                'r2r_jitminopts'             : ['COMPlus_TieredCompilation' : '0', "COMPlus_JITMinOpts": "1"], 
145                'r2r_jitforcerelocs'         : ['COMPlus_TieredCompilation' : '0', "COMPlus_ForceRelocs": "1"],
146                'r2r_gcstress15'             : ['COMPlus_TieredCompilation' : '0', "COMPlus_GCStress": "0xF"],
147                'r2r_no_tiered_compilation'  : ['COMPlus_TieredCompilation' : '0'],
148     ]
149
150     // This is the basic set of scenarios
151     def static basicScenarios = [
152                'innerloop',
153                'normal',
154                'ilrt',
155                'r2r',
156                'longgc',
157                'formatting',
158                'gcsimulator',
159                // 'jitdiff', // jitdiff is currently disabled, until someone spends the effort to make it fully work
160                'standalone_gc',
161                'gc_reliability_framework',
162                'illink',
163                'corefx_innerloop',
164                'crossgen_comparison',
165                'pmi_asm_diffs']
166
167     def static allScenarios = basicScenarios + r2rStressScenarios.keySet() + jitStressModeScenarios.keySet()
168
169     // Valid PR trigger combinations.
170     def static prTriggeredValidInnerLoopCombos = [
171         'Windows_NT': [
172             'x64': [
173                 'Checked'
174             ], 
175             'x86': [
176                 'Checked',
177                 'Release'
178             ], 
179             'arm': [
180                 'Debug',
181                 'Checked'
182             ],
183             'arm64': [
184                 'Debug',
185                 'Checked'
186             ]
187         ],
188         'Windows_NT_BuildOnly': [
189             'x64': [
190                 'Checked',
191                 'Release'
192             ],
193             'x86': [
194                 'Checked',
195                 'Release'
196             ], 
197             'arm': [
198                 'Checked'
199             ], 
200         ],
201         'Ubuntu': [
202             'x64': [
203                 'Checked'
204             ],
205             'arm': [
206                 'Checked'
207             ]
208         ],
209         'Ubuntu16.04': [
210             'arm64': [
211                 'Checked'
212             ]
213         ],
214         'CentOS7.1': [
215             'x64': [
216                 'Debug',
217                 'Checked'
218             ]
219         ],
220         'OSX10.12': [
221             'x64': [
222                 'Checked'
223             ]
224         ],
225         'Tizen': [
226             'armem': [
227                 'Checked'
228             ]
229         ]
230     ]
231
232     // A set of scenarios that are valid for arm/arm64 tests run on hardware. This is a map from valid scenario name
233     // to Tests.lst file categories to exclude.
234     //
235     // This list should contain a subset of the scenarios from `allScenarios`. Please keep this in the same order as that,
236     // and with the same values, with some commented out, for easier maintenance.
237     //
238     // Note that some scenarios that are commented out should be enabled, but haven't yet been.
239     //
240     def static validArmWindowsScenarios = [
241                'innerloop',
242                'normal',
243                // 'ilrt'
244                'r2r',
245                // 'longgc'
246                // 'formatting'
247                // 'gcsimulator'
248                // 'jitdiff'
249                // 'standalone_gc'
250                // 'gc_reliability_framework'
251                // 'illink'
252                // 'corefx_innerloop'
253                // 'crossgen_comparison'
254                // 'pmi_asm_diffs'
255                'r2r_jitstress1',
256                'r2r_jitstress2',
257                'r2r_jitstress1_tiered',
258                'r2r_jitstress2_tiered',
259                'r2r_jitstressregs1',
260                'r2r_jitstressregs2',
261                'r2r_jitstressregs3',
262                'r2r_jitstressregs4',
263                'r2r_jitstressregs8',
264                'r2r_jitstressregs0x10',
265                'r2r_jitstressregs0x80',
266                'r2r_jitstressregs0x1000',
267                'r2r_jitminopts',
268                'r2r_jitforcerelocs',
269                'r2r_gcstress15',
270                'r2r_no_tiered_compilation',
271                'minopts',
272                'tieredcompilation',
273                'no_tiered_compilation',
274                'no_tiered_compilation_innerloop',
275                'forcerelocs',
276                'jitstress1',
277                'jitstress2',
278                'jitstress1_tiered',
279                'jitstress2_tiered',
280                'jitstressregs1',
281                'jitstressregs2',
282                'jitstressregs3',
283                'jitstressregs4',
284                'jitstressregs8',
285                'jitstressregs0x10',
286                'jitstressregs0x80',
287                'jitstressregs0x1000',
288                'jitstress2_jitstressregs1',
289                'jitstress2_jitstressregs2',
290                'jitstress2_jitstressregs3',
291                'jitstress2_jitstressregs4',
292                'jitstress2_jitstressregs8',
293                'jitstress2_jitstressregs0x10',
294                'jitstress2_jitstressregs0x80',
295                'jitstress2_jitstressregs0x1000',
296                'tailcallstress',
297                // 'jitsse2only'                     // Only relevant to xarch
298                'jitnosimd',                         // Only interesting on platforms where SIMD support exists.
299                // 'jitincompletehwintrinsic'
300                // 'jitx86hwintrinsicnoavx'
301                // 'jitx86hwintrinsicnoavx2'
302                // 'jitx86hwintrinsicnosimd'
303                // 'jitnox86hwintrinsic'
304                'corefx_baseline',                   // corefx tests don't use smarty
305                'corefx_minopts',                    // corefx tests don't use smarty
306                'corefx_tieredcompilation',          // corefx tests don't use smarty
307                'corefx_jitstress1',                 // corefx tests don't use smarty
308                'corefx_jitstress2',                 // corefx tests don't use smarty
309                'corefx_jitstressregs1',             // corefx tests don't use smarty
310                'corefx_jitstressregs2',             // corefx tests don't use smarty
311                'corefx_jitstressregs3',             // corefx tests don't use smarty
312                'corefx_jitstressregs4',             // corefx tests don't use smarty
313                'corefx_jitstressregs8',             // corefx tests don't use smarty
314                'corefx_jitstressregs0x10',          // corefx tests don't use smarty
315                'corefx_jitstressregs0x80',          // corefx tests don't use smarty
316                'corefx_jitstressregs0x1000',        // corefx tests don't use smarty
317                'gcstress0x3',
318                'gcstress0xc',
319                'zapdisable',
320                'heapverify1',
321                'gcstress0xc_zapdisable',
322                'gcstress0xc_zapdisable_jitstress2',
323                'gcstress0xc_zapdisable_heapverify1',
324                'gcstress0xc_jitstress1',
325                'gcstress0xc_jitstress2',
326                'gcstress0xc_minopts_heapverify1',
327
328                //
329                // NOTE: the following scenarios are not defined in the 'allScenarios' list! Is this a bug?
330                //
331
332                'minopts_zapdisable',
333                'gcstress0x3_jitstress1',
334                'gcstress0x3_jitstress2',
335                'gcstress0x3_jitstressregs1',
336                'gcstress0x3_jitstressregs2',
337                'gcstress0x3_jitstressregs3',
338                'gcstress0x3_jitstressregs4',
339                'gcstress0x3_jitstressregs8',
340                'gcstress0x3_jitstressregs0x10',
341                'gcstress0x3_jitstressregs0x80',
342                'gcstress0x3_jitstressregs0x1000',
343                'gcstress0xc_jitstressregs1',
344                'gcstress0xc_jitstressregs2',
345                'gcstress0xc_jitstressregs3',
346                'gcstress0xc_jitstressregs4',
347                'gcstress0xc_jitstressregs8',
348                'gcstress0xc_jitstressregs0x10',
349                'gcstress0xc_jitstressregs0x80',
350                'gcstress0xc_jitstressregs0x1000'
351     ]
352   
353     def static validLinuxArmScenarios = [
354                'innerloop',
355                'normal',
356                // 'ilrt'
357                'r2r',
358                // 'longgc'
359                // 'formatting'
360                // 'gcsimulator'
361                // 'jitdiff'
362                // 'standalone_gc'
363                // 'gc_reliability_framework'
364                // 'illink'
365                // 'corefx_innerloop'
366                'crossgen_comparison',
367                'pmi_asm_diffs',
368                'r2r_jitstress1',
369                'r2r_jitstress2',
370                'r2r_jitstress1_tiered',
371                'r2r_jitstress2_tiered',
372                'r2r_jitstressregs1',
373                'r2r_jitstressregs2',
374                'r2r_jitstressregs3',
375                'r2r_jitstressregs4',
376                'r2r_jitstressregs8',
377                'r2r_jitstressregs0x10',
378                'r2r_jitstressregs0x80',
379                'r2r_jitstressregs0x1000',
380                'r2r_jitminopts',
381                'r2r_jitforcerelocs',
382                'r2r_gcstress15',
383                'r2r_no_tiered_compilation',
384                'minopts',
385                'tieredcompilation',
386                'no_tiered_compilation',
387                'no_tiered_compilation_innerloop',
388                'forcerelocs',
389                'jitstress1',
390                'jitstress2',
391                'jitstress1_tiered',
392                'jitstress2_tiered',
393                'jitstressregs1',
394                'jitstressregs2',
395                'jitstressregs3',
396                'jitstressregs4',
397                'jitstressregs8',
398                'jitstressregs0x10',
399                'jitstressregs0x80',
400                'jitstressregs0x1000',
401                'jitstress2_jitstressregs1',
402                'jitstress2_jitstressregs2',
403                'jitstress2_jitstressregs3',
404                'jitstress2_jitstressregs4',
405                'jitstress2_jitstressregs8',
406                'jitstress2_jitstressregs0x10',
407                'jitstress2_jitstressregs0x80',
408                'jitstress2_jitstressregs0x1000',
409                'tailcallstress',
410                // 'jitsse2only'                          // Only relevant to xarch
411                // 'jitnosimd'                            // Only interesting on platforms where SIMD support exists.
412                // 'jitincompletehwintrinsic'
413                // 'jitx86hwintrinsicnoavx'
414                // 'jitx86hwintrinsicnoavx2'
415                // 'jitx86hwintrinsicnosimd'
416                // 'jitnox86hwintrinsic'
417                'corefx_baseline',
418                'corefx_minopts',
419                'corefx_tieredcompilation',
420                'corefx_jitstress1',
421                'corefx_jitstress2',
422                'corefx_jitstressregs1',
423                'corefx_jitstressregs2',
424                'corefx_jitstressregs3',
425                'corefx_jitstressregs4',
426                'corefx_jitstressregs8',
427                'corefx_jitstressregs0x10',
428                'corefx_jitstressregs0x80',
429                'corefx_jitstressregs0x1000',
430                'gcstress0x3',
431                'gcstress0xc',
432                'zapdisable',
433                'heapverify1',
434                'gcstress0xc_zapdisable',
435                'gcstress0xc_zapdisable_jitstress2',
436                'gcstress0xc_zapdisable_heapverify1',
437                'gcstress0xc_jitstress1',
438                'gcstress0xc_jitstress2',
439                'gcstress0xc_minopts_heapverify1'
440     ]
441
442     def static validLinuxArm64Scenarios = [
443                'innerloop',
444                'normal',
445                // 'ilrt'
446                'r2r',
447                // 'longgc'
448                // 'formatting'
449                // 'gcsimulator'
450                // 'jitdiff'
451                // 'standalone_gc'
452                // 'gc_reliability_framework'
453                // 'illink'
454                // 'corefx_innerloop'
455                'crossgen_comparison',
456                'pmi_asm_diffs',
457                'r2r_jitstress1',
458                'r2r_jitstress2',
459                'r2r_jitstress1_tiered',
460                'r2r_jitstress2_tiered',
461                'r2r_jitstressregs1',
462                'r2r_jitstressregs2',
463                'r2r_jitstressregs3',
464                'r2r_jitstressregs4',
465                'r2r_jitstressregs8',
466                'r2r_jitstressregs0x10',
467                'r2r_jitstressregs0x80',
468                'r2r_jitstressregs0x1000',
469                'r2r_jitminopts',
470                'r2r_jitforcerelocs',
471                'r2r_gcstress15',
472                'r2r_no_tiered_compilation',
473                'minopts',
474                'tieredcompilation',
475                'no_tiered_compilation',
476                'no_tiered_compilation_innerloop',
477                'forcerelocs',
478                'jitstress1',
479                'jitstress2',
480                'jitstress1_tiered',
481                'jitstress2_tiered',
482                'jitstressregs1',
483                'jitstressregs2',
484                'jitstressregs3',
485                'jitstressregs4',
486                'jitstressregs8',
487                'jitstressregs0x10',
488                'jitstressregs0x80',
489                'jitstressregs0x1000',
490                'jitstress2_jitstressregs1',
491                'jitstress2_jitstressregs2',
492                'jitstress2_jitstressregs3',
493                'jitstress2_jitstressregs4',
494                'jitstress2_jitstressregs8',
495                'jitstress2_jitstressregs0x10',
496                'jitstress2_jitstressregs0x80',
497                'jitstress2_jitstressregs0x1000',
498                'tailcallstress',
499                // 'jitsse2only'                         // Only relevant to xarch
500                'jitnosimd',                             // Only interesting on platforms where SIMD support exists.
501                // 'jitincompletehwintrinsic'
502                // 'jitx86hwintrinsicnoavx'
503                // 'jitx86hwintrinsicnoavx2'
504                // 'jitx86hwintrinsicnosimd'
505                // 'jitnox86hwintrinsic'
506                'corefx_baseline',
507                'corefx_minopts',
508                'corefx_tieredcompilation',
509                'corefx_jitstress1',
510                'corefx_jitstress2',
511                'corefx_jitstressregs1',
512                'corefx_jitstressregs2',
513                'corefx_jitstressregs3',
514                'corefx_jitstressregs4',
515                'corefx_jitstressregs8',
516                'corefx_jitstressregs0x10',
517                'corefx_jitstressregs0x80',
518                'corefx_jitstressregs0x1000',
519                'gcstress0x3',
520                'gcstress0xc',
521                'zapdisable',
522                'heapverify1',
523                'gcstress0xc_zapdisable',
524                'gcstress0xc_zapdisable_jitstress2',
525                'gcstress0xc_zapdisable_heapverify1',
526                'gcstress0xc_jitstress1',
527                'gcstress0xc_jitstress2',
528                'gcstress0xc_minopts_heapverify1'
529     ]
530
531     def static configurationList = ['Debug', 'Checked', 'Release']
532
533     // This is the set of architectures
534     // Some of these are pseudo-architectures:
535     //    armem -- ARM builds/runs using an emulator. Used for Tizen runs.
536     def static architectureList = ['arm', 'armem', 'arm64', 'x64', 'x86']
537
538     // This set of architectures that cross build on Windows and run on Windows ARM64 hardware.
539     def static armWindowsCrossArchitectureList = ['arm', 'arm64']
540 }
541
542 // **************************************************************
543 // Create some specific views
544 // 
545 // These aren't using the Utilities.addStandardFolderView() function, because that creates
546 // views based on a single regular expression. These views will be generated by adding a
547 // specific set of jobs to them.
548 //
549 // Utilities.addStandardFolderView() also creates a lot of additional stuff around the
550 // view, like "Build Statistics", "Job Statistics", "Unstable Jobs". Until it is determined
551 // those are required, don't add them (which simplifies the view pages, as well).
552 // **************************************************************
553
554 class Views {
555     def static MergeJobView = null
556     def static PeriodicJobView = null
557     def static ArchitectureViews = [:]
558     def static OSViews = [:]
559 }
560
561 // MergeJobView: include all jobs that execute when a PR change is merged.
562 Views.MergeJobView = listView('Merge') {
563     recurse()
564     columns {
565         status()
566         weather()
567         name()
568         lastSuccess()
569         lastFailure()
570         lastDuration()
571         buildButton()
572     }
573 }
574
575 // PeriodicJobView: include all jobs that execute on a schedule
576 Views.PeriodicJobView = listView('Periodic') {
577     recurse()
578     columns {
579         status()
580         weather()
581         name()
582         lastSuccess()
583         lastFailure()
584         lastDuration()
585         buildButton()
586     }
587 }
588
589 // Create a view for non-PR jobs for each architecture.
590 Constants.architectureList.each { architecture ->
591     Views.ArchitectureViews[architecture] = listView(architecture) {
592         recurse()
593         columns {
594             status()
595             weather()
596             name()
597             lastSuccess()
598             lastFailure()
599             lastDuration()
600             buildButton()
601         }
602     }
603 }
604
605 // Create a view for non-PR jobs for each OS.
606 Constants.osList.each { os ->
607     // Don't create one for the special 'Windows_NT_BuildOnly'
608     if (os == 'Windows_NT_BuildOnly') {
609         return
610     }
611     Views.OSViews[os] = listView(os) {
612         recurse()
613         columns {
614             status()
615             weather()
616             name()
617             lastSuccess()
618             lastFailure()
619             lastDuration()
620             buildButton()
621         }
622     }
623 }
624
625 def static addToMergeView(def job) {
626     Views.MergeJobView.with {
627         jobs {
628             name(job.name)
629         }
630     }
631 }
632
633 def static addToPeriodicView(def job) {
634     Views.PeriodicJobView.with {
635         jobs {
636             name(job.name)
637         }
638     }
639 }
640
641 def static addToViews(def job, def isFlowJob, def isPR, def architecture, def os, def configuration, def scenario) {
642     if (isPR) {
643         // No views want PR jobs currently.
644         return
645     }
646
647     // We don't want to include in view any job that is only used by a flow job (because we want the views to have only the
648     // "top-level" jobs. Build only jobs are such jobs.
649     if (os == 'Windows_NT_BuildOnly') {
650         return
651     }
652
653     if (!isFlowJob) {
654         // For non-flow jobs, which ones are only used by flow jobs?
655         if ((architecture == 'arm') || (architecture == 'arm64')) {
656             if (isCoreFxScenario(scenario)) {
657                 // We have corefx-specific scenario builds for each of the runs, but these are driven by flow jobs.
658                 return
659             }
660
661             // We're left with the basic normal/innerloop builds. We might want to remove these from the views also, if desired.
662             // However, there are a few, like the Debug Build, that is build only, not "Build and Test", that we should leave.
663         }
664     }
665
666     // Add to architecture view.
667     Views.ArchitectureViews[architecture].with {
668         jobs {
669             name(job.name)
670         }
671     }
672
673     // Add to OS view.
674     Views.OSViews[os].with {
675         jobs {
676             name(job.name)
677         }
678     }
679 }
680
681 def static addPeriodicTriggerHelper(def job, String cronString, boolean alwaysRuns = false) {
682     addToPeriodicView(job)
683     Utilities.addPeriodicTrigger(job, cronString, alwaysRuns)
684 }
685
686 def static addGithubPushTriggerHelper(def job) {
687     addToMergeView(job)
688     Utilities.addGithubPushTrigger(job)
689 }
690
691
692 def static setMachineAffinity(def job, def os, def architecture, def options = null) {
693     assert os instanceof String
694     assert architecture instanceof String
695
696     def armArches = ['arm', 'armem', 'arm64']
697
698     if (!(architecture in armArches)) {
699         assert options == null
700         Utilities.setMachineAffinity(job, os, 'latest-or-auto')
701
702         return
703     }
704
705     // This is an arm(64) job.
706     //
707     // There are several options.
708     //
709     // Windows_NT
710     // 
711     // Arm32 (Build) -> latest-arm64
712     //       |-> os == "Windows_NT" && (architecture == "arm") && options['use_arm64_build_machine'] == true
713     // Arm32 (Test)  -> arm64-windows_nt
714     //       |-> os == "Windows_NT" && (architecture == "arm") && options['use_arm64_build_machine'] == false
715     //
716     // Arm64 (Build) -> latest-arm64
717     //       |-> os == "Windows_NT" && architecture == "arm64" && options['use_arm64_build_machine'] == true
718     // Arm64 (Test)  -> arm64-windows_nt
719     //       |-> os == "Windows_NT" && architecture == "arm64" && options['use_arm64_build_machine'] == false
720     //
721     // Ubuntu
722     //
723     // Arm32 emulator (Build, Test) -> arm-cross-latest
724     //       |-> os == "Tizen" && (architecture == "armem")
725     //
726     // Arm32 hardware (Flow) -> Ubuntu 16.04 latest-or-auto (don't use limited arm hardware)
727     //       |-> os == "Ubuntu" && (architecture == "arm") && options['is_flow_job'] == true
728     // Arm32 hardware (Build) -> Ubuntu 16.04 latest-or-auto
729     //       |-> os == "Ubuntu" && (architecture == "arm") && options['is_build_job'] == true
730     // Arm32 hardware (Test) -> Helix ubuntu.1404.arm32.open queue
731     //       |-> os == "Ubuntu" && (architecture == "arm")
732     //
733     // Arm64 (Build) -> arm64-cross-latest
734     //       |-> os != "Windows_NT" && architecture == "arm64" && options['is_build_job'] == true
735     // Arm64 (Test) -> Helix Ubuntu.1604.Arm64.Open queue
736     //       |-> os != "Windows_NT" && architecture == "arm64"
737     //
738     // Note: we are no longer using Jenkins tags "arm64-huge-page-size", "arm64-small-page-size".
739     // Support for Linux arm64 large page size has been removed for now, as it wasn't being used.
740     //
741     // Note: we are no longer using Jenkins tag 'latest-arm64' for arm/arm64 Windows build machines. Instead,
742     // we are using public VS2017 arm/arm64 tools in a VM from Helix.
743
744     // This has to be a arm arch
745     assert architecture in armArches
746     if (os == "Windows_NT") {
747         // arm32/arm64 Windows jobs share the same machines for now
748         def isBuild = options['use_arm64_build_machine'] == true
749
750         if (isBuild == true) {
751             job.with {
752                 label('Windows.10.Amd64.ClientRS4.DevEx.Open')
753             }
754         } else {
755             Utilities.setMachineAffinity(job, 'windows.10.arm64.open')
756         }
757     } else {
758         assert os != 'Windows_NT'
759
760         if (architecture == 'armem') {
761             // arm emulator (Tizen). Build and test on same machine,
762             // using Docker.
763             assert os == 'Tizen'
764             Utilities.setMachineAffinity(job, 'Ubuntu', 'arm-cross-latest')
765         }
766         else {
767             // arm/arm64 Ubuntu on hardware.
768             assert architecture == 'arm' || architecture == 'arm64'
769             def isFlow  = (options != null) && (options['is_flow_job'] == true)
770             def isBuild = (options != null) && (options['is_build_job'] == true)
771             if (isFlow || isBuild) {
772                 // arm/arm64 Ubuntu build machine. Build uses docker, so the actual host OS is not
773                 // very important. Therefore, use latest or auto. Flow jobs don't need to use arm hardware.
774                 Utilities.setMachineAffinity(job, 'Ubuntu16.04', 'latest-or-auto')
775             } else {
776                 // arm/arm64 Ubuntu test machine. Specify the Helix queue name here.
777                 if (architecture == 'arm64') {
778                     assert os == 'Ubuntu16.04'
779                     job.with {
780                         label('Ubuntu.1604.Arm64.Open')
781                     }
782                 }
783                 else {
784                     assert os == 'Ubuntu'
785                     job.with {
786                         label('ubuntu.1404.arm32.open')
787                     }
788                 }
789             }
790         }
791     }
792 }
793
794 // setJobMachineAffinity: compute the machine affinity options for a job,
795 // then set the job with those affinity options.
796 def static setJobMachineAffinity(def architecture, def os, def isBuildJob, def isTestJob, def isFlowJob, def job)
797 {
798     assert (isBuildJob  && !isTestJob && !isFlowJob) ||
799            (!isBuildJob && isTestJob  && !isFlowJob) ||
800            (!isBuildJob && !isTestJob && isFlowJob)
801
802     def affinityOptions = null
803     def affinityArchitecture = architecture
804
805     if (os == "Windows_NT") {
806         if (architecture in Constants.armWindowsCrossArchitectureList) {
807             if (isBuildJob) {
808                 affinityOptions = [ "use_arm64_build_machine" : true ]
809             } else if (isTestJob) {
810                 affinityOptions = [ "use_arm64_build_machine" : false ]
811             } else if (isFlowJob) {
812                 // For the flow jobs set the machine affinity as x64
813                 affinityArchitecture = 'x64'
814             }
815         }
816     }
817     else {
818         if ((architecture == 'arm64') || (architecture == 'arm')) {
819             if (isBuildJob) {
820                 affinityOptions = ['is_build_job': true]
821             } else if (isFlowJob) {
822                 affinityOptions = ['is_flow_job': true]
823             }
824         }
825     }
826
827     setMachineAffinity(job, os, affinityArchitecture, affinityOptions)
828 }
829
830 def static isGCStressRelatedTesting(def scenario) {
831     // The 'r2r_gcstress15' scenario is a basic scenario.
832     // Detect it and make it a GCStress related.
833     if (scenario == 'r2r_gcstress15')
834     {
835         return true;
836     }
837
838     def gcStressTestEnvVars = [ 'COMPlus_GCStress', 'COMPlus_ZapDisable', 'COMPlus_HeapVerify']
839     def scenarioName = scenario.toLowerCase()
840     def isGCStressTesting = false
841     Constants.jitStressModeScenarios[scenario].each{ k, v ->
842         if (k in gcStressTestEnvVars) {
843             isGCStressTesting = true;
844         }
845     }
846     return isGCStressTesting
847 }
848
849 def static isCoreFxScenario(def scenario) {
850     def corefx_prefix = 'corefx_'
851     if (scenario.length() < corefx_prefix.length()) {
852         return false
853     }
854     return scenario.substring(0,corefx_prefix.length()) == corefx_prefix
855 }
856
857 def static isR2RBaselineScenario(def scenario) {
858     return (scenario == 'r2r')
859 }
860
861 def static isR2RStressScenario(def scenario) {
862     return Constants.r2rStressScenarios.containsKey(scenario)
863 }
864
865 def static isR2RScenario(def scenario) {
866     return isR2RBaselineScenario(scenario) || isR2RStressScenario(scenario)
867 }
868
869 def static isJitStressScenario(def scenario) {
870     return Constants.jitStressModeScenarios.containsKey(scenario)
871 }
872
873 def static isLongGc(def scenario) {
874     return (scenario == 'longgc' || scenario == 'gcsimulator')
875 }
876
877 def static isJitDiff(def scenario) {
878     return (scenario == 'jitdiff')
879 }
880
881 def static isGcReliabilityFramework(def scenario) {
882     return (scenario == 'gc_reliability_framework')
883 }
884
885 def static isArmWindowsScenario(def scenario) {
886     return Constants.validArmWindowsScenarios.contains(scenario)
887 }
888
889 def static isValidPrTriggeredInnerLoopJob(os, architecture, configuration, isBuildOnly) {
890     if (isBuildOnly == true) {
891         os = 'Windows_NT_BuildOnly'
892     }
893
894     def validOsPrTriggerArchConfigs = Constants.prTriggeredValidInnerLoopCombos[os]
895     if (validOsPrTriggerArchConfigs != null) {
896         def validOsPrTriggerConfigs = validOsPrTriggerArchConfigs[architecture]
897         if (validOsPrTriggerConfigs != null) {
898             if (configuration in validOsPrTriggerConfigs) {
899                 return true
900             }
901         }
902     }
903
904     return false
905 }
906
907 // This means the job builds and runs the 'innerloop' test set. This does not mean the job is 
908 // scheduled with a default PR trigger despite the correlation being true at the moment.
909 def static isInnerloopTestScenario(def scenario) {
910     return (scenario == 'innerloop' || scenario == 'no_tiered_compilation_innerloop')
911 }
912
913 def static isCrossGenComparisonScenario(def scenario) {
914     return (scenario == 'crossgen_comparison')
915 }
916
917 def static shouldGenerateCrossGenComparisonJob(def os, def architecture, def configuration, def scenario) {
918     assert isCrossGenComparisonScenario(scenario)
919     return ((os == 'Ubuntu' && architecture == 'arm') || (os == 'Ubuntu16.04' && architecture == 'arm64')) && (configuration == 'Checked' || configuration == 'Release')
920 }
921
922 def static getFxBranch(def branch) {
923     def fxBranch = branch
924     // Map 'dev/unix_test_workflow' to 'master' so we can test CoreFX jobs in the CoreCLR dev/unix_test_workflow
925     // branch even though CoreFX doesn't have such a branch.
926     if (branch == 'dev/unix_test_workflow') {
927         fxBranch = 'master'
928     }
929     return fxBranch
930 }
931
932 def static setJobTimeout(newJob, isPR, architecture, configuration, scenario, isBuildOnly) {
933     // 2 hours (120 minutes) is the default timeout
934     def timeout = 120
935
936     if (!isInnerloopTestScenario(scenario)) {
937         // Pri-1 test builds take a long time (see calculateBuildCommands()). So up the Pri-1 build jobs timeout.
938         timeout = 240
939     }
940
941     if (!isBuildOnly) {
942         // Note that these can only increase, never decrease, the Pri-1 timeout possibly set above.
943         if (isGCStressRelatedTesting(scenario)) {
944             timeout = 4320
945         }
946         else if (isCoreFxScenario(scenario)) {
947             timeout = 360
948         }
949         else if (isJitStressScenario(scenario)) {
950             timeout = 300
951         }
952         else if (isR2RBaselineScenario(scenario)) {
953             timeout = 240
954         }
955         else if (isLongGc(scenario)) {
956             timeout = 1440
957         }
958         else if (isJitDiff(scenario)) {
959             timeout = 240
960         }
961         else if (isGcReliabilityFramework(scenario)) {
962             timeout = 1440
963         }
964         else if (architecture == 'armem' || architecture == 'arm64') {
965             timeout = 240
966         }
967
968         if (architecture == 'arm') {
969             // ARM32 machines are particularly slow.
970             timeout += 120
971         }
972     }
973
974     if (configuration == 'Debug') {
975         // Debug runs can be very slow. Add an hour.
976         timeout += 60
977     }
978
979     // If we've changed the timeout from the default, set it in the job.
980
981     if (timeout != 120) {
982         Utilities.setJobTimeout(newJob, timeout)
983     }
984 }
985
986 def static getJobFolder(def scenario) {
987     if (isJitStressScenario(scenario) || isR2RStressScenario(scenario)) {
988         return 'jitstress'
989     }
990     if (scenario == 'illink') {
991         return 'illink'
992     }
993     return ''
994 }
995
996 def static getStressModeDisplayName(def scenario) {
997     def displayStr = ''
998     Constants.jitStressModeScenarios[scenario].each{ k, v ->
999         def prefixLength = 'COMPlus_'.length()
1000         if (k.length() >= prefixLength) {
1001             def modeName = k.substring(prefixLength, k.length())
1002             if (displayStr != '') {
1003                 // Separate multiple variables with a space.
1004                 displayStr += ' '
1005             }
1006             displayStr += modeName + '=' + v
1007         }
1008     }
1009
1010     if (isCoreFxScenario(scenario)) {
1011         displayStr = ('CoreFx ' + displayStr).trim()
1012     }
1013
1014     return displayStr
1015 }
1016
1017 def static getR2RDisplayName(def scenario) {
1018     // Assume the scenario name is one from the r2rStressScenarios dict, and remove its "r2r_" prefix.
1019     def displayStr = scenario
1020     def prefixLength = 'r2r_'.length()
1021     if (displayStr.length() >= prefixLength) {
1022         displayStr = "R2R " + displayStr.substring(prefixLength, displayStr.length())
1023     } else if (scenario == 'r2r') {
1024         displayStr = "R2R"
1025     }
1026     return displayStr
1027 }
1028
1029 def static getScenarioDisplayString(def scenario) {
1030     switch (scenario) {
1031         case 'innerloop':
1032             return "Innerloop Build and Test"
1033
1034         case 'no_tiered_compilation_innerloop':
1035             def displayStr = getStressModeDisplayName(scenario)
1036             return "Innerloop Build and Test (Jit - ${displayStr})"
1037
1038         case 'corefx_innerloop':
1039             return "CoreFX Tests"
1040
1041         case 'normal':
1042             return "Build and Test"
1043
1044         case 'jitdiff':
1045             return "Jit Diff Build and Test"
1046
1047         case 'ilrt':
1048             return "IL RoundTrip Build and Test"
1049
1050         case 'longgc':
1051             return "Long-Running GC Build & Test"
1052
1053         case 'gcsimulator':
1054             return "GC Simulator"
1055
1056         case 'standalone_gc':
1057             return "Standalone GC"
1058
1059         case 'gc_reliability_framework':
1060             return "GC Reliability Framework"
1061
1062         case 'illink':
1063             return "via ILLink"
1064
1065         default:
1066             if (isJitStressScenario(scenario)) {
1067                 def displayStr = getStressModeDisplayName(scenario)
1068                 return "Build and Test (Jit - ${displayStr})"
1069             }
1070             else if (isR2RScenario(scenario)) {
1071                 def displayStr = getR2RDisplayName(scenario)
1072                 return "${displayStr} Build and Test"
1073             }
1074             else {
1075                 return "${scenario}"
1076             }
1077             break
1078     }
1079
1080     println("Unknown scenario: ${scenario}");
1081     assert false
1082 }
1083
1084 //
1085 // Functions to create an environment script.
1086 //      envScriptCreate -- initialize the script (call first)
1087 //      envScriptFinalize -- finalize the script (call last)
1088 //      envScriptSetStressModeVariables -- set stress mode variables in the env script
1089 //      envScriptAppendExistingScript -- append an existing script to the generated script
1090 //
1091 // Each script returns a string of commands. Concatenate all the strings together before
1092 // adding them to the builds commands, to make sure they get executed as one Jenkins script.
1093 //
1094
1095 // Initialize the environment setting script.
1096 def static envScriptCreate(def os, def stepScriptLocation) {
1097     def stepScript = ''
1098     if (os == 'Windows_NT') {
1099         stepScript += "echo Creating TestEnv script\r\n"
1100         stepScript += "if exist ${stepScriptLocation} del ${stepScriptLocation}\r\n"
1101
1102         // Create at least an empty script.
1103         stepScript += "echo. > ${stepScriptLocation}\r\n"
1104     }
1105     else {
1106         stepScript += "echo Creating environment setting script\n"
1107         stepScript += "echo \\#\\!/usr/bin/env bash > ${stepScriptLocation}\n"
1108     }
1109
1110     return stepScript
1111 }
1112
1113 // Generates the string for setting stress mode variables.
1114 def static envScriptSetStressModeVariables(def os, def stressModeVars, def stepScriptLocation) {
1115     def stepScript = ''
1116     if (os == 'Windows_NT') {
1117         stressModeVars.each{ k, v ->
1118             // Write out what we are writing to the script file
1119             stepScript += "echo Setting ${k}=${v}\r\n"
1120             // Write out the set itself to the script file`
1121             stepScript += "echo set ${k}=${v} >> ${stepScriptLocation}\r\n"
1122         }
1123     }
1124     else {
1125         stressModeVars.each{ k, v ->
1126             // Write out what we are writing to the script file
1127             stepScript += "echo Setting ${k}=${v}\n"
1128             // Write out the set itself to the script file`
1129             stepScript += "echo export ${k}=${v} >> ${stepScriptLocation}\n"
1130         }
1131     }
1132
1133     return stepScript
1134 }
1135
1136 // Append an existing script to an environment script.
1137 // Returns string of commands to do this.
1138 def static envScriptAppendExistingScript(def os, def appendScript, def stepScriptLocation) {
1139     assert (os == 'Windows_NT')
1140     def stepScript = ''
1141
1142     stepScript += "echo Appending ${appendScript} to ${stepScriptLocation}\r\n"
1143     stepScript += "type ${appendScript} >> ${stepScriptLocation}\r\n"
1144
1145     return stepScript
1146 }
1147
1148 // Finalize an environment setting script.
1149 // Returns string of commands to do this.
1150 def static envScriptFinalize(def os, def stepScriptLocation) {
1151     def stepScript = ''
1152
1153     if (os == 'Windows_NT') {
1154         // Display the resulting script. This is useful when looking at the output log file.
1155         stepScript += "echo Display the total script ${stepScriptLocation}\r\n"
1156         stepScript += "type ${stepScriptLocation}\r\n"
1157     }
1158     else {
1159         stepScript += "chmod +x ${stepScriptLocation}\n"
1160     }
1161
1162     return stepScript
1163 }
1164
1165 def static isNeedDocker(def architecture, def os, def isBuild) {
1166     if (isBuild) {
1167         if (architecture == 'x86' && os == 'Ubuntu') {
1168             return true
1169         }
1170         else if (architecture == 'armem') {
1171             return true
1172         }
1173         else if (architecture == 'arm') {
1174             if (os == 'Ubuntu') {
1175                 return true
1176             }
1177         }
1178         else if (architecture == 'arm64') {
1179             if (os == 'Ubuntu16.04') {
1180                 return true
1181             }
1182         }
1183     }
1184     else {
1185         if (architecture == 'x86' && os == 'Ubuntu') {
1186             return true
1187         }
1188     }
1189     return false
1190 }
1191
1192 def static getDockerImageName(def architecture, def os, def isBuild) {
1193     // We must change some docker private images to official later
1194     if (isBuild) {
1195         if (architecture == 'x86' && os == 'Ubuntu') {
1196             return "hseok82/dotnet-buildtools-prereqs:ubuntu-16.04-crossx86-ef0ac75-20175511035548"
1197         }
1198         else if (architecture == 'armem') {
1199             if (os == 'Tizen') {
1200                 return "tizendotnet/dotnet-buildtools-prereqs:ubuntu-16.04-cross-e435274-20180426002255-tizen-rootfs-5.0m1"
1201             }
1202         }
1203         else if (architecture == 'arm') {
1204             if (os == 'Ubuntu') {
1205                 return "microsoft/dotnet-buildtools-prereqs:ubuntu-14.04-cross-e435274-20180426002420"
1206             }
1207         }
1208         else if (architecture == 'arm64') {
1209             if (os == 'Ubuntu16.04') {
1210                 return "microsoft/dotnet-buildtools-prereqs:ubuntu-16.04-cross-arm64-a3ae44b-20180315221921"
1211             }
1212         }
1213     }
1214     else {
1215         if (architecture == 'x86' && os == 'Ubuntu') {
1216             return "hseok82/dotnet-buildtools-prereqs:ubuntu1604_x86_test"
1217         }
1218     }
1219     println("Unknown architecture to use docker: ${architecture} ${os}");
1220     assert false
1221 }
1222
1223 def static getTestArtifactsTgzFileName(def osGroup, def architecture, def configuration) {
1224     return "bin-tests-${osGroup}.${architecture}.${configuration}.tgz"
1225 }
1226
1227 // We have a limited amount of some hardware. For these, scale back the periodic testing we do,
1228 // and only allowing using this hardware in some specific branches.
1229 def static jobRequiresLimitedHardware(def architecture, def os) {
1230     if (architecture == 'arm') {
1231         // arm Windows and Linux hardware is limited.
1232         return true
1233     }
1234     else if (architecture == 'arm64') {
1235         // arm64 Windows and Linux hardware is limited.
1236         return true
1237     }
1238     else {
1239         return false
1240     }
1241 }
1242
1243 // Calculates the name of the build job based on some typical parameters.
1244 //
1245 def static getJobName(def configuration, def architecture, def os, def scenario, def isBuildOnly) {
1246     // If the architecture is x64, do not add that info into the build name.
1247     // Need to change around some systems and other builds to pick up the right builds
1248     // to do that.
1249
1250     def suffix = scenario != 'normal' ? "_${scenario}" : '';
1251     if (isBuildOnly) {
1252         suffix += '_bld'
1253     }
1254     def baseName = ''
1255     switch (architecture) {
1256         case 'x64':
1257             if (scenario == 'normal') {
1258                 // For now we leave x64 off of the name for compatibility with other jobs
1259                 baseName = configuration.toLowerCase() + '_' + os.toLowerCase()
1260             }
1261             else if (scenario == 'formatting') {
1262                 // we don't care about the configuration for the formatting job. It runs all configs
1263                 baseName = architecture.toLowerCase() + '_' + os.toLowerCase()
1264             }
1265             else {
1266                 baseName = architecture.toLowerCase() + '_' + configuration.toLowerCase() + '_' + os.toLowerCase()
1267             }
1268             break
1269         case 'armem':
1270             // These are cross builds
1271             assert os == 'Tizen'
1272             baseName = 'armel_cross_' + configuration.toLowerCase() + '_' + os.toLowerCase()
1273             break
1274         case 'arm':
1275         case 'arm64':
1276             // These are cross builds
1277             baseName = architecture.toLowerCase() + '_cross_' + configuration.toLowerCase() + '_' + os.toLowerCase()
1278             break
1279         case 'x86':
1280             baseName = architecture.toLowerCase() + '_' + configuration.toLowerCase() + '_' + os.toLowerCase()
1281             break
1282         default:
1283             println("Unknown architecture: ${architecture}");
1284             assert false
1285             break
1286     }
1287
1288     return baseName + suffix
1289 }
1290
1291 def static addNonPRTriggers(def job, def branch, def isPR, def architecture, def os, def configuration, def scenario, def isFlowJob, def isWindowsBuildOnlyJob, def bidailyCrossList) {
1292
1293     // The dev/unix_test_workflow branch is used for Jenkins CI testing. We generally do not need any non-PR
1294     // triggers in the branch, because that would use machine resources unnecessarily.
1295     if (branch == 'dev/unix_test_workflow') {
1296         return
1297     }
1298
1299     // Limited hardware is restricted for non-PR triggers to certain branches.
1300     if (jobRequiresLimitedHardware(architecture, os) && (!(branch in Constants.LimitedHardwareBranches))) {
1301         return
1302     }
1303
1304     // Ubuntu x86 CI jobs are failing. Disable non-PR triggered jobs to avoid these constant failures
1305     // until this is fixed. Tracked by https://github.com/dotnet/coreclr/issues/19003.
1306     if (architecture == 'x86' && os == 'Ubuntu') {
1307         return
1308     }
1309
1310     def isNormalOrInnerloop = (scenario == "normal" || scenario == "innerloop")
1311
1312     // Check scenario.
1313     switch (scenario) {
1314         case 'crossgen_comparison':
1315             if (isFlowJob && ((os == 'Ubuntu' && architecture == 'arm') || (os == 'Ubuntu16.04' && architecture == 'arm64')) && (configuration == 'Checked' || configuration == 'Release')) {
1316                 addPeriodicTriggerHelper(job, '@daily')
1317             }
1318             break
1319
1320         case 'pmi_asm_diffs':
1321             // No non-PR triggers for now.
1322             break
1323
1324         case 'normal':
1325             switch (architecture) {
1326                 case 'x64':
1327                 case 'x86':
1328                     if (isFlowJob && architecture == 'x86' && os == 'Ubuntu') {
1329                         addPeriodicTriggerHelper(job, '@daily')
1330                     }
1331                     else if (isFlowJob || os == 'Windows_NT' || (architecture == 'x64' && !(os in Constants.crossList))) {
1332                         addGithubPushTriggerHelper(job)
1333                     }
1334                     break
1335                 case 'arm64':
1336                     if (os == 'Windows_NT') {
1337                         if (isFlowJob || (isNormalOrInnerloop && (configuration == 'Debug'))) {
1338                             // We would normally want a per-push trigger, but with limited hardware we can't keep up.
1339                             // Do the builds daily.
1340                             addPeriodicTriggerHelper(job, '@daily')
1341                         }
1342                     }
1343                     else {
1344                         // Only the flow jobs get push triggers; the build and test jobs are triggered by the flow job.
1345                         if (isFlowJob) {
1346                             addPeriodicTriggerHelper(job, '@daily')
1347                         }
1348                     }
1349                     break
1350                 case 'arm':
1351                     if (os == 'Windows_NT') {
1352                         if (isFlowJob || (isNormalOrInnerloop && (configuration == 'Debug'))) {
1353                             // We would normally want a push trigger, but with limited hardware we can't keep up.
1354                             // Do the builds daily.
1355                             addPeriodicTriggerHelper(job, '@daily')
1356                         }
1357                     }
1358                     else {
1359                         assert os == 'Ubuntu'
1360                         // Only the flow jobs get push triggers; the build and test jobs are triggered by the flow job.
1361                         if (isFlowJob) {
1362                             // Currently no push triggers, with limited arm Linux hardware.
1363                             // TODO: If we have enough machine capacity, add some arm Linux push triggers.
1364                             addPeriodicTriggerHelper(job, '@daily')
1365                         }
1366                     }
1367                     break
1368                 case 'armem':
1369                     addGithubPushTriggerHelper(job)
1370                     break
1371                 default:
1372                     println("Unknown architecture: ${architecture}");
1373                     assert false
1374                     break
1375             }
1376             break
1377         case 'r2r':
1378             assert !(os in bidailyCrossList)
1379             // r2r gets a push trigger for checked/release
1380             if (configuration == 'Checked' || configuration == 'Release') {
1381                 if (architecture == 'x64' && os != 'OSX10.12') {
1382                     //Flow jobs should be Windows, Ubuntu, OSX0.12, or CentOS
1383                     if (isFlowJob || os == 'Windows_NT') {
1384                         addGithubPushTriggerHelper(job)
1385                     }
1386                 // OSX10.12 r2r jobs should only run every 12 hours, not daily.
1387                 } else if (architecture == 'x64' && os == 'OSX10.12'){
1388                     if (isFlowJob) {
1389                         addPeriodicTriggerHelper(job, 'H H/12 * * *')
1390                     }
1391                 }
1392                 // For x86, only add per-commit jobs for Windows
1393                 else if (architecture == 'x86') {
1394                     if (os == 'Windows_NT') {
1395                         addGithubPushTriggerHelper(job)
1396                     }
1397                 }
1398                 // arm r2r jobs should only run weekly.
1399                 else if (architecture == 'arm') {
1400                     if (isFlowJob) {
1401                         addPeriodicTriggerHelper(job, '@weekly')
1402                     }
1403                 }
1404                 // arm64 r2r jobs should only run weekly.
1405                 else if (architecture == 'arm64') {
1406                     if (isFlowJob) {
1407                         addPeriodicTriggerHelper(job, '@weekly')
1408                     }
1409                 }
1410             }
1411             break
1412         case 'r2r_jitstress1':
1413         case 'r2r_jitstress2':
1414         case 'r2r_jitstress1_tiered':
1415         case 'r2r_jitstress2_tiered':
1416         case 'r2r_jitstressregs1':
1417         case 'r2r_jitstressregs2':
1418         case 'r2r_jitstressregs3':
1419         case 'r2r_jitstressregs4':
1420         case 'r2r_jitstressregs8':
1421         case 'r2r_jitstressregs0x10':
1422         case 'r2r_jitstressregs0x80':
1423         case 'r2r_jitstressregs0x1000':
1424         case 'r2r_jitminopts':
1425         case 'r2r_jitforcerelocs':
1426         case 'r2r_gcstress15':
1427         case 'r2r_no_tiered_compilation':
1428             assert !(os in bidailyCrossList)
1429
1430             // GCStress=C is currently not supported on OS X
1431             if (os == 'OSX10.12' && isGCStressRelatedTesting(scenario)) {
1432                 break
1433             }
1434
1435             if (configuration == 'Checked' || configuration == 'Release') {
1436                 if (architecture == 'x64') {
1437                     //Flow jobs should be Windows, Ubuntu, OSX10.12, or CentOS
1438                     if (isFlowJob || os == 'Windows_NT') {
1439                         addPeriodicTriggerHelper(job, 'H H * * 3,6') // some time every Wednesday and Saturday
1440                     }
1441                 }
1442                 // For x86, only add periodic jobs for Windows
1443                 else if (architecture == 'x86') {
1444                     if (os == 'Windows_NT') {
1445                         addPeriodicTriggerHelper(job, 'H H * * 3,6') // some time every Wednesday and Saturday
1446                     }
1447                 }
1448                 else if (architecture == 'arm') {
1449                     if (isFlowJob) {
1450                         addPeriodicTriggerHelper(job, '@weekly')
1451                     }
1452                 }
1453                 else if (architecture == 'arm64') {
1454                     if (isFlowJob) {
1455                         addPeriodicTriggerHelper(job, '@weekly')
1456                     }
1457                 }
1458             }
1459             break
1460         case 'longgc':
1461             assert (os == 'Ubuntu' || os == 'Windows_NT' || os == 'OSX10.12')
1462             assert configuration == 'Release'
1463             assert architecture == 'x64'
1464             addPeriodicTriggerHelper(job, '@daily')
1465             // TODO: Add once external email sending is available again
1466             // addEmailPublisher(job, 'dotnetgctests@microsoft.com')
1467             break
1468         case 'gcsimulator':
1469             assert (os == 'Ubuntu' || os == 'Windows_NT' || os == 'OSX10.12')
1470             assert configuration == 'Release'
1471             assert architecture == 'x64'
1472             addPeriodicTriggerHelper(job, 'H H * * 3,6') // some time every Wednesday and Saturday
1473             // TODO: Add once external email sending is available again
1474             // addEmailPublisher(job, 'dotnetgctests@microsoft.com')
1475             break
1476         case 'standalone_gc':
1477             assert (os == 'Ubuntu' || os == 'Windows_NT' || os == 'OSX10.12')
1478             assert (configuration == 'Release' || configuration == 'Checked')
1479             // TODO: Add once external email sending is available again
1480             // addEmailPublisher(job, 'dotnetgctests@microsoft.com')
1481             addPeriodicTriggerHelper(job, '@daily')
1482             break
1483         case 'gc_reliability_framework':
1484             assert (os == 'Ubuntu' || os == 'Windows_NT' || os == 'OSX10.12')
1485             assert (configuration == 'Release' || configuration == 'Checked')
1486             // Only triggered by phrase.
1487             break
1488         case 'ilrt':
1489             assert !(os in bidailyCrossList)
1490             // ILASM/ILDASM roundtrip one gets a daily build, and only for release
1491             if (architecture == 'x64' && configuration == 'Release') {
1492                 if (isFlowJob || os == 'Windows_NT') {
1493                     addPeriodicTriggerHelper(job, '@daily')
1494                 }
1495             }
1496             break
1497         case 'jitdiff':
1498             assert (os == 'Ubuntu' || os == 'Windows_NT' || os == 'OSX10.12')
1499             assert configuration == 'Checked'
1500             assert (architecture == 'x64' || architecture == 'x86')
1501             addGithubPushTriggerHelper(job)
1502             break
1503         case 'formatting':
1504             assert (os == 'Windows_NT' || os == "Ubuntu")
1505             assert architecture == 'x64'
1506             addGithubPushTriggerHelper(job)
1507             break
1508         case 'jitstressregs1':
1509         case 'jitstressregs2':
1510         case 'jitstressregs3':
1511         case 'jitstressregs4':
1512         case 'jitstressregs8':
1513         case 'jitstressregs0x10':
1514         case 'jitstressregs0x80':
1515         case 'jitstressregs0x1000':
1516         case 'minopts':
1517         case 'tieredcompilation':
1518         case 'no_tiered_compilation':
1519         case 'forcerelocs':
1520         case 'jitstress1':
1521         case 'jitstress2':
1522         case 'jitstress1_tiered':
1523         case 'jitstress2_tiered':
1524         case 'jitstress2_jitstressregs1':
1525         case 'jitstress2_jitstressregs2':
1526         case 'jitstress2_jitstressregs3':
1527         case 'jitstress2_jitstressregs4':
1528         case 'jitstress2_jitstressregs8':
1529         case 'jitstress2_jitstressregs0x10':
1530         case 'jitstress2_jitstressregs0x80':
1531         case 'jitstress2_jitstressregs0x1000':
1532         case 'tailcallstress':
1533         case 'jitsse2only':
1534         case 'jitnosimd':
1535         case 'jitnox86hwintrinsic':
1536         case 'jitincompletehwintrinsic':
1537         case 'jitx86hwintrinsicnoavx':
1538         case 'jitx86hwintrinsicnoavx2':
1539         case 'jitx86hwintrinsicnosimd':
1540         case 'corefx_baseline':
1541         case 'corefx_minopts':
1542         case 'corefx_tieredcompilation':
1543         case 'corefx_jitstress1':
1544         case 'corefx_jitstress2':
1545         case 'corefx_jitstressregs1':
1546         case 'corefx_jitstressregs2':
1547         case 'corefx_jitstressregs3':
1548         case 'corefx_jitstressregs4':
1549         case 'corefx_jitstressregs8':
1550         case 'corefx_jitstressregs0x10':
1551         case 'corefx_jitstressregs0x80':
1552         case 'corefx_jitstressregs0x1000':
1553         case 'zapdisable':
1554             if (os == 'CentOS7.1') {
1555                 break
1556             }
1557             if (os in bidailyCrossList) {
1558                 break
1559             }
1560             // ARM corefx testing uses non-flow jobs to provide the configuration-specific
1561             // build for the flow job. We don't need cron jobs for these. Note that the
1562             // Windows ARM jobs depend on a Windows "build only" job that exits the trigger
1563             // function very early, so only non-Windows gets here.
1564             if ((architecture == 'arm') && isCoreFxScenario(scenario) && !isFlowJob) {
1565                 break
1566             }
1567             if ((architecture == 'arm64') && isCoreFxScenario(scenario) && !isFlowJob) {
1568                 break
1569             }
1570             if (jobRequiresLimitedHardware(architecture, os)) {
1571                 if ((architecture == 'arm64') && (os == 'Ubuntu16.04')) {
1572                     // These jobs are very fast on Linux/arm64 hardware, so run them daily.
1573                     addPeriodicTriggerHelper(job, '@daily')
1574                 }
1575                 else {
1576                     addPeriodicTriggerHelper(job, '@weekly')
1577                 }
1578             }
1579             else {
1580                 addPeriodicTriggerHelper(job, '@daily')
1581             }
1582             break
1583         case 'heapverify1':
1584         case 'gcstress0x3':
1585             if (os == 'CentOS7.1') {
1586                 break
1587             }
1588             if (os in bidailyCrossList) {
1589                 break
1590             }
1591             addPeriodicTriggerHelper(job, '@weekly')
1592             break
1593         case 'gcstress0xc':
1594         case 'gcstress0xc_zapdisable':
1595         case 'gcstress0xc_zapdisable_jitstress2':
1596         case 'gcstress0xc_zapdisable_heapverify1':
1597         case 'gcstress0xc_jitstress1':
1598         case 'gcstress0xc_jitstress2':
1599         case 'gcstress0xc_minopts_heapverify1':
1600             if (os == 'OSX10.12') {
1601                 // GCStress=C is currently not supported on OS X
1602                 break
1603             }
1604             if (os == 'CentOS7.1') {
1605                 break
1606             }
1607             if (os in bidailyCrossList) {
1608                 break
1609             }
1610             addPeriodicTriggerHelper(job, '@weekly')
1611             break
1612
1613         case 'illink':
1614             // Testing on other operating systems TBD
1615             assert (os == 'Windows_NT' || os == 'Ubuntu')
1616             if (architecture == 'x64' || architecture == 'x86') {
1617                 if (configuration == 'Checked') {
1618                     addPeriodicTriggerHelper(job, '@daily')
1619                 }
1620             }
1621             break
1622
1623         default:
1624             println("Unknown scenario: ${scenario}");
1625             assert false
1626             break
1627     }
1628     return
1629 }
1630
1631 // **************************
1632 // Define the basic inner loop builds for PR and commit.  This is basically just the set
1633 // of coreclr builds over linux/osx 10.12/windows and debug/release/checked.  In addition, the windows
1634 // builds will do a couple extra steps.
1635 // **************************
1636
1637 // Adds a trigger for the PR build if one is needed.  If isFlowJob is true, then this is the
1638 // flow job that rolls up the build and test for non-windows OS's.  // If the job is a windows build only job,
1639 // it's just used for internal builds
1640 // If you add a job with a trigger phrase, please add that phrase to coreclr/Documentation/project-docs/ci-trigger-phrases.md
1641 def static addTriggers(def job, def branch, def isPR, def architecture, def os, def configuration, def scenario, def isFlowJob, def isWindowsBuildOnlyJob) {
1642     def isNormalOrInnerloop = (scenario == "normal" || scenario == "innerloop")
1643     
1644     if (isWindowsBuildOnlyJob) {
1645         return
1646     }
1647
1648     def bidailyCrossList = ['RHEL7.2', 'Debian8.4']
1649     // Non pull request builds.
1650     if (!isPR) {
1651         addNonPRTriggers(job, branch, isPR, architecture, os, configuration, scenario, isFlowJob, isWindowsBuildOnlyJob, bidailyCrossList)
1652         return
1653     }
1654
1655     def arm64Users = [
1656         'adityamandaleeka',
1657         'AndyAyersMS',
1658         'briansull',
1659         'BruceForstall',
1660         'CarolEidt',
1661         'davidwrighton',
1662         'echesakovMSFT',
1663         'erozenfeld',
1664         'janvorli',
1665         'jashook',
1666         'pgodeq',
1667         'RussKeldorph',
1668         'sandreenko',
1669         'sdmaclea',
1670         'swaroop-sridhar',
1671         'jkotas',
1672         'markwilkie',
1673         'weshaggard'
1674     ]
1675
1676     // Pull request builds.  Generally these fall into two categories: default triggers and on-demand triggers
1677     // We generally only have a distinct set of default triggers but a bunch of on-demand ones.
1678
1679     def contextString = ""
1680     def triggerString = ""
1681     def needsTrigger = true
1682     def isDefaultTrigger = false
1683     def isArm64PrivateJob = false
1684     def scenarioString = ""
1685
1686     // Set up default context string and trigger phrases. This is overridden in places, sometimes just to keep
1687     // the existing non-standard descriptions and phrases. In some cases, the scenarios are asymmetric, as for
1688     // some jobs where the Debug configuration just does builds, no tests.
1689     //
1690     // Some configurations, like arm32/arm64, always use the exact scenario name as part of the context string.
1691     // This makes it possible to copy/paste the displayed context string as "@dotnet-bot test <context-string>"
1692     // to invoke the trigger. Any "fancy" context string makes that impossible, requiring the user to either 
1693     // remember the mapping from context string to trigger string, or use "@dotnet-bot help" to look it up.
1694
1695     if (architecture == 'armem') {
1696         assert os == 'Tizen'
1697         architecture = 'armel'
1698     }
1699
1700     switch (architecture) {
1701         case 'armel':
1702         case 'arm':
1703         case 'arm64':
1704             contextString = "${os} ${architecture} Cross ${configuration}"
1705             triggerString = "(?i).*test\\W+${os}\\W+${architecture}\\W+Cross\\W+${configuration}"
1706
1707             if (scenario == 'innerloop') {
1708                 contextString += " Innerloop"
1709                 triggerString += "\\W+Innerloop"
1710             }
1711             else {
1712                 contextString += " ${scenario}"
1713                 triggerString += "\\W+${scenario}"
1714             }
1715
1716             if (scenario == 'pmi_asm_diffs') {
1717                 // Don't add the "Build and Test" part
1718             }
1719             else if (configuration == 'Debug') {
1720                 contextString += " Build"
1721                 triggerString += "\\W+Build"
1722             }
1723             else {
1724                 contextString += " Build and Test"
1725                 triggerString += "\\W+Build and Test"
1726             }
1727
1728             triggerString += ".*"
1729             break
1730
1731         default:
1732             scenarioString = getScenarioDisplayString(scenario)
1733             contextString = "${os} ${architecture} ${configuration} ${scenarioString}"
1734             triggerString = "(?i).*test\\W+${os}\\W+${architecture}\\W+${configuration}"
1735
1736             switch (scenario) {
1737                 case 'normal':
1738                     triggerString += "\\W+Build and Test.*"
1739                     break
1740
1741                 case 'corefx_innerloop': // maintain this asymmetry
1742                     triggerString += "\\W+CoreFX Tests.*"
1743                     break
1744
1745                 default:
1746                     triggerString += "\\W+${scenario}.*"
1747                     break
1748             }
1749
1750             triggerString += ".*"
1751             break
1752     }
1753
1754     // Now determine what kind of trigger this job needs, if any. Any job should be triggerable, except for
1755     // non-flow jobs that are only used as part of flow jobs.
1756
1757     switch (architecture) {
1758         case 'x64': // editor brace matching: {
1759             if (scenario == 'formatting') {
1760                 assert configuration == 'Checked'
1761                 if (os == 'Windows_NT' || os == 'Ubuntu') {
1762                     isDefaultTrigger = true
1763                     contextString = "${os} ${architecture} Formatting"
1764                 }
1765                 break
1766             }
1767
1768             if (scenario == 'pmi_asm_diffs') {
1769                 // Everything is already set.
1770                 // No default triggers.
1771                 break
1772             }
1773
1774             switch (os) {
1775                 // OpenSUSE, Debian & RedHat get trigger phrases for pri 0 build, and pri 1 build & test
1776                 case 'Debian8.4':
1777                 case 'RHEL7.2':
1778                     if (scenario == 'innerloop') {
1779                         assert !isFlowJob
1780                         contextString = "${os} ${architecture} ${configuration} Innerloop Build"
1781                         isDefaultTrigger = true
1782                         break
1783                     }
1784
1785                     // fall through
1786
1787                 case 'Fedora24':
1788                 case 'Ubuntu16.04':
1789                 case 'Ubuntu16.10':
1790                     assert !isFlowJob
1791                     assert scenario != 'innerloop'
1792                     contextString = "${os} ${architecture} ${configuration} Build"
1793                     triggerString = "(?i).*test\\W+${os}\\W+${architecture}\\W+${configuration}\\W+Build.*"
1794                     break
1795
1796                 case 'Ubuntu':
1797                     if (scenario == 'illink') {
1798                         break
1799                     }
1800                     else if (scenario == 'corefx_innerloop') {
1801                         if (configuration == 'Checked') {
1802                             isDefaultTrigger = true
1803                         }
1804                         break
1805                     }
1806
1807                     // fall through
1808
1809                 case 'OSX10.12':
1810                     // Triggers on the non-flow jobs aren't necessary here
1811                     // Corefx testing uses non-flow jobs.
1812                     if (!isFlowJob && !isCoreFxScenario(scenario)) {
1813                         needsTrigger = false
1814                         break
1815                     }
1816                     switch (scenario) {
1817                         case 'innerloop':
1818                             isDefaultTrigger = true
1819                             break
1820
1821                         case 'no_tiered_compilation_innerloop':
1822                             if (os == 'Ubuntu') {
1823                                 isDefaultTrigger = true
1824                             }
1825                             break
1826
1827                         default:
1828                             break
1829                     }
1830                     break
1831
1832                 case 'CentOS7.1':
1833                     switch (scenario) {
1834                         case 'innerloop':
1835                             // CentOS uses checked for default PR tests while debug is build only
1836                             if (configuration == 'Debug') {
1837                                 isDefaultTrigger = true
1838                                 contextString = "${os} ${architecture} ${configuration} Innerloop Build"
1839                                 break
1840                             }
1841                             
1842                             // Make sure this is a flow job to get build and test.
1843                             if (!isFlowJob) {
1844                                 needsTrigger = false
1845                                 break
1846                             }
1847
1848                             if (configuration == 'Checked') {
1849                                 assert job.name.contains("flow")
1850                                 isDefaultTrigger = true
1851                                 contextString = "${os} ${architecture} ${configuration} Innerloop Build and Test"
1852                             }
1853                             break
1854
1855                         case 'normal':
1856                             // Make sure this is a flow job to get build and test.
1857                             if (!isFlowJob) {
1858                                 needsTrigger = false
1859                                 break
1860                             }
1861                             break
1862
1863                         default:
1864                             break
1865                     }
1866                     break
1867
1868                 case 'Windows_NT':
1869                     switch (scenario) {
1870                         case 'innerloop':
1871                         case 'no_tiered_compilation_innerloop':
1872                             isDefaultTrigger = true
1873                             break
1874
1875                         case 'corefx_innerloop':
1876                             if (configuration == 'Checked' || configuration == 'Release') {
1877                                 isDefaultTrigger = true
1878                             }
1879                             break
1880
1881                         default:
1882                             break
1883                     }
1884                     break
1885
1886                 default:
1887                     println("Unknown os: ${os}");
1888                     assert false
1889                     break
1890
1891             } // switch (os)
1892
1893             break
1894         // editor brace matching: }
1895
1896         case 'armel': // editor brace matching: {
1897             job.with {
1898                 publishers {
1899                     azureVMAgentPostBuildAction {
1900                         agentPostBuildAction('Delete agent if the build was not successful (when idle).')
1901                     }
1902                 }
1903             }
1904
1905             switch (os) {
1906                 case 'Tizen':
1907                     if (scenario == 'innerloop') {
1908                         if (configuration == 'Checked') {
1909                             isDefaultTrigger = true
1910                         }
1911                     }
1912                     break
1913             }
1914
1915             break
1916         // editor brace matching: }
1917
1918         case 'arm':
1919         case 'arm64': // editor brace matching: {
1920
1921             switch (os) {
1922                 case 'Ubuntu':
1923                 case 'Ubuntu16.04':
1924
1925                     // Triggers on the non-flow jobs aren't necessary
1926                     if (!isFlowJob) {
1927                         needsTrigger = false
1928                         break
1929                     }
1930
1931                     switch (scenario) {
1932                         case 'innerloop':
1933                         case 'no_tiered_compilation_innerloop':
1934                             if (configuration == 'Checked') {
1935                                 isDefaultTrigger = true
1936                             }
1937                             break
1938                          case 'crossgen_comparison':
1939                             if (os == 'Ubuntu' && architecture == 'arm' && (configuration == 'Checked' || configuration == 'Release')) {
1940                                 isDefaultTrigger = true
1941                             }
1942                             break
1943                     }
1944                     break
1945
1946                 case 'Windows_NT':
1947                     assert isArmWindowsScenario(scenario)
1948
1949                     // For Debug normal/innerloop scenario, we don't do test runs, so we don't use flow jobs. That means we need a trigger for
1950                     // the non-flow Build job. All others need a trigger on the flow job.
1951                     def needsFlowJobTrigger = !(isNormalOrInnerloop && (configuration == 'Debug'))
1952                     if (isFlowJob != needsFlowJobTrigger) {
1953                         needsTrigger = false
1954                         break
1955                     }
1956
1957                     switch (scenario) {
1958                         case 'innerloop':
1959                             if (configuration == 'Debug') {
1960                                 // Add default PR trigger for Windows arm64 Debug builds. This is a build only -- no tests are run --
1961                                 // so the private test hardware is not used. Thus, it can be run by all users, not just arm64Users.
1962                                 // People in arm64Users will get both this and the Checked Build and Test job.
1963                                 isDefaultTrigger = true
1964                             } else if (configuration == 'Checked') {
1965                                 isDefaultTrigger = true
1966                                 isArm64PrivateJob = true
1967                             }
1968                             break
1969                         default:
1970                             isArm64PrivateJob = true
1971                             break
1972                     }
1973                     break
1974                 default:
1975                     println("NYI os: ${os}");
1976                     assert false
1977                     break
1978             }
1979             break
1980
1981         // editor brace matching: }
1982         case 'x86': // editor brace matching: {
1983             assert ((os == 'Windows_NT') || ((os == 'Ubuntu') && isNormalOrInnerloop))
1984             if (os == 'Ubuntu') {
1985                 // Triggers on the non-flow jobs aren't necessary here
1986                 if (!isFlowJob) {
1987                     needsTrigger = false
1988                     break
1989                 }
1990                 
1991                 // on-demand only for ubuntu x86
1992                 contextString = "${os} ${architecture} ${configuration} Build"
1993                 triggerString = "(?i).*test\\W+${os}\\W+${architecture}\\W+${configuration}.*"
1994                 break
1995             }
1996             switch (scenario) {
1997                 case 'innerloop':
1998                 case 'no_tiered_compilation_innerloop':
1999                     isDefaultTrigger = true
2000                     break
2001                 default:
2002                     break
2003             }
2004             break
2005
2006         // editor brace matching: }
2007
2008         default:
2009             println("Unknown architecture: ${architecture}");
2010             assert false
2011             break
2012     }
2013
2014     if (needsTrigger) {
2015         if (isArm64PrivateJob) {
2016             if (isDefaultTrigger) {
2017                 Utilities.addDefaultPrivateGithubPRTriggerForBranch(job, branch, contextString, null, arm64Users)
2018             }
2019             else {
2020                 Utilities.addPrivateGithubPRTriggerForBranch(job, branch, contextString, triggerString, null, arm64Users)
2021             }
2022         }
2023         else {
2024             if (isDefaultTrigger) {
2025                 Utilities.addGithubPRTriggerForBranch(job, branch, contextString)
2026             }
2027             else {
2028                 Utilities.addGithubPRTriggerForBranch(job, branch, contextString, triggerString)
2029             }
2030         }
2031     }
2032 }
2033
2034 def static calculateBuildCommands(def newJob, def scenario, def branch, def isPR, def architecture, def configuration, def os, def isBuildOnly) {
2035     def buildCommands = []
2036     def osGroup = getOSGroup(os)
2037     def lowerConfiguration = configuration.toLowerCase()
2038
2039     // Which set of tests to build? Innerloop tests build Pri-0.
2040     // Currently, we only generate asm diffs on Pri-0 tests, if we generate asm diffs on tests at all.
2041     // CoreFX testing skipts building tests altogether (done below).
2042     // All other scenarios build Pri-1 tests.
2043     def priority = '1'
2044     if (isInnerloopTestScenario(scenario)) {
2045         priority = '0'
2046     }
2047
2048     def doCoreFxTesting = isCoreFxScenario(scenario)
2049
2050     def buildCoreclrTests = true
2051     if (doCoreFxTesting || (scenario == 'pmi_asm_diffs')) {
2052         // These scenarios don't need the coreclr tests build.
2053         buildCoreclrTests = false
2054     }
2055
2056     // Calculate the build steps, archival, and xunit results
2057     switch (os) {
2058         case 'Windows_NT': // editor brace matching: {
2059             switch (architecture) {
2060                 case 'x64':
2061                 case 'x86':
2062                     def arch = architecture
2063                     def buildOpts = ''
2064
2065                     if (scenario == 'formatting') {
2066                         buildCommands += "python -u tests\\scripts\\format.py -c %WORKSPACE% -o Windows_NT -a ${arch}"
2067                         Utilities.addArchival(newJob, "format.patch", "", true, false)
2068                         break
2069                     }
2070
2071                     if (scenario == 'illink') {
2072                         buildCommands += "tests\\scripts\\build_illink.cmd clone ${arch}"
2073                     }
2074
2075                     // If it is a release build for Windows, ensure PGO is used, else fail the build.
2076                     if ((lowerConfiguration == 'release') &&
2077                         (scenario in Constants.basicScenarios)) {
2078
2079                         buildOpts += ' -enforcepgo'
2080                     }
2081
2082                     if (buildCoreclrTests) {
2083                         buildOpts += " -priority=${priority}"
2084                     } else {
2085                         buildOpts += ' skiptests';
2086                     }
2087
2088                     // Set __TestIntermediateDir to something short. If __TestIntermediateDir is already set, build-test.cmd will
2089                     // output test binaries to that directory. If it is not set, the binaries are sent to a default directory whose name is about
2090                     // 35 characters long.
2091
2092                     buildCommands += "set __TestIntermediateDir=int&&build.cmd ${lowerConfiguration} ${arch} ${buildOpts}"
2093
2094                     if (scenario == 'pmi_asm_diffs') {
2095                         // Now, generate the layout. We don't have any tests, but we need to restore the packages before calling runtest.cmd.
2096                         // Call build-test.cmd to do this. It will do a little more than we need, but that's ok.
2097                         buildCommands += "build-test.cmd ${lowerConfiguration} ${arch} skipmanaged skipnative"
2098                         buildCommands += "tests\\runtest.cmd ${lowerConfiguration} ${arch} GenerateLayoutOnly"
2099
2100                         // TODO: Add -target_branch and -commit_hash arguments based on GitHub variables.
2101                         buildCommands += "python -u %WORKSPACE%\\tests\\scripts\\run-pmi-diffs.py -arch ${arch} -ci_arch ${architecture} -build_type ${configuration}"
2102
2103                         // ZIP up the asm
2104                         buildCommands += "powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::CreateFromDirectory('_\\pmi\\asm', '.\\dasm.${os}.${architecture}.${configuration}.zip')\"";
2105
2106                         // Archive the asm
2107                         Utilities.addArchival(newJob, "dasm.${os}.${architecture}.${configuration}.zip")
2108                         break
2109                     }
2110
2111                     if (!isBuildOnly) {
2112                         def runtestArguments = ''
2113                         def testOpts = 'collectdumps'
2114
2115                         if (isR2RScenario(scenario)) {
2116
2117                             // If this is a ReadyToRun scenario, pass 'crossgen'
2118                             // to cause framework assemblies to be crossgen'ed. Pass 'runcrossgentests'
2119                             // to cause the tests to be crossgen'ed.
2120
2121                             testOpts += ' crossgen runcrossgentests'
2122                         }
2123                         else if (scenario == 'jitdiff') {
2124                             testOpts += ' jitdisasm crossgen'
2125                         }
2126                         else if (scenario == 'ilrt') {
2127                             testOpts += ' ilasmroundtrip'
2128                         }
2129                         else if (isLongGc(scenario)) {
2130                             testOpts += " ${scenario} sequential"
2131                         }
2132                         else if (scenario == 'standalone_gc') {
2133                             testOpts += ' gcname clrgc.dll'
2134                         }
2135                         else if (scenario == 'illink') {
2136                             testOpts += " link %WORKSPACE%\\linker\\linker\\bin\\netcore_Release\\netcoreapp2.0\\win10-${arch}\\publish\\illink.exe"
2137                         }
2138
2139                         // Default per-test timeout is 10 minutes. For stress modes and Debug scenarios, increase this
2140                         // to 30 minutes (30 * 60 * 1000 = 180000). The "timeout" argument to runtest.cmd sets this, by
2141                         // taking a timeout value in milliseconds. (Note that it sets the __TestTimeout environment variable,
2142                         // which is read by the xunit harness.)
2143                         if (isJitStressScenario(scenario) || isR2RStressScenario(scenario) || (lowerConfiguration == 'debug'))
2144                         {
2145                             def timeout = 1800000
2146                             testOpts += " timeout ${timeout}"
2147                         }
2148
2149                         // If we are running a stress mode, we should write out the set of key
2150                         // value env pairs to a file at this point and then we'll pass that to runtest.cmd
2151
2152                         def envScriptPath = ''
2153                         if (isJitStressScenario(scenario) || isR2RStressScenario(scenario)) {
2154                             def buildCommandsStr = ''
2155                             envScriptPath = "%WORKSPACE%\\SetStressModes.bat"
2156                             buildCommandsStr += envScriptCreate(os, envScriptPath)
2157
2158                             if (isJitStressScenario(scenario)) {
2159                                 buildCommandsStr += envScriptSetStressModeVariables(os, Constants.jitStressModeScenarios[scenario], envScriptPath)
2160                             }
2161                             else if (isR2RStressScenario(scenario)) {
2162                                 buildCommandsStr += envScriptSetStressModeVariables(os, Constants.r2rStressScenarios[scenario], envScriptPath)
2163                             }
2164
2165                             envScriptFinalize(os, envScriptPath)
2166
2167                             // Note that buildCommands is an array of individually executed commands; we want all the commands used to 
2168                             // create the SetStressModes.bat script to be executed together, hence we accumulate them as strings
2169                             // into a single script.
2170                             buildCommands += buildCommandsStr
2171                         }
2172                         if (envScriptPath != '') {
2173                             testOpts += " TestEnv ${envScriptPath}"
2174                         }
2175
2176                         runtestArguments = "${lowerConfiguration} ${arch} ${testOpts}"
2177
2178                         if (doCoreFxTesting) {
2179                             if (scenario == 'corefx_innerloop') {
2180                                 // Create CORE_ROOT and testhost
2181                                 buildCommands += "build-test.cmd ${lowerConfiguration} ${arch} buildtesthostonly"                                
2182                                 buildCommands += "tests\\runtest.cmd ${runtestArguments} CoreFXTestsAll"
2183
2184                                 // Archive and process (only) the test results
2185                                 Utilities.addArchival(newJob, "bin/Logs/**/testResults.xml")
2186                                 Utilities.addXUnitDotNETResults(newJob, "bin/Logs/**/testResults.xml")
2187                             }
2188                             else {
2189                                 def workspaceRelativeFxRoot = "_/fx"
2190                                 def absoluteFxRoot = "%WORKSPACE%\\_\\fx"
2191                                 def fxBranch = getFxBranch(branch)
2192
2193                                 buildCommands += "python -u %WORKSPACE%\\tests\\scripts\\run-corefx-tests.py -arch ${arch} -ci_arch ${architecture} -build_type ${configuration} -fx_root ${absoluteFxRoot} -fx_branch ${fxBranch} -env_script ${envScriptPath}"
2194
2195                                 // Archive and process (only) the test results
2196                                 Utilities.addArchival(newJob, "${workspaceRelativeFxRoot}/artifacts/bin/**/testResults.xml")
2197                                 Utilities.addXUnitDotNETResults(newJob, "${workspaceRelativeFxRoot}/artifacts/bin/**/testResults.xml")
2198
2199                                 //Archive additional build stuff to diagnose why my attempt at fault injection isn't causing CI to fail
2200                                 Utilities.addArchival(newJob, "SetStressModes.bat", "", true, false)
2201                                 Utilities.addArchival(newJob, "${workspaceRelativeFxRoot}/artifacts/bin/testhost/**", "", true, false)
2202                             }
2203                         }
2204                         else if (isGcReliabilityFramework(scenario)) {
2205                             buildCommands += "tests\\runtest.cmd ${runtestArguments} GenerateLayoutOnly"
2206                             buildCommands += "tests\\scripts\\run-gc-reliability-framework.cmd ${arch} ${configuration}"
2207                         }
2208                         else {
2209                             def buildCommandsStr = "call tests\\runtest.cmd ${runtestArguments}\r\n"
2210                             if (!isBuildOnly) {
2211                                 // If we ran the tests, collect the test logs collected by xunit. We want to do this even if the tests fail, so we
2212                                 // must do it in the same batch file as the test run.
2213
2214                                 buildCommandsStr += "echo on\r\n" // Show the following commands in the log. "echo" doesn't alter the errorlevel.
2215                                 buildCommandsStr += "set saved_errorlevel=%errorlevel%\r\n"
2216                                 buildCommandsStr += "powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::CreateFromDirectory('.\\bin\\tests\\${osGroup}.${arch}.${configuration}\\Reports', '.\\bin\\tests\\testReports.zip')\"\r\n";
2217                                 buildCommandsStr += "exit /b %saved_errorlevel%\r\n"
2218
2219                                 def doNotFailIfNothingArchived = true
2220                                 def archiveOnlyIfSuccessful = false
2221                                 Utilities.addArchival(newJob, "bin/tests/testReports.zip", "", doNotFailIfNothingArchived, archiveOnlyIfSuccessful)
2222                             }
2223                             buildCommands += buildCommandsStr
2224                         }
2225                     } // end if (!isBuildOnly)
2226
2227                     if (!doCoreFxTesting) {
2228                         // Run the rest of the build
2229                         // Build the mscorlib for the other OS's
2230                         buildCommands += "build.cmd ${lowerConfiguration} ${arch} linuxmscorlib"
2231                         buildCommands += "build.cmd ${lowerConfiguration} ${arch} osxmscorlib"
2232                        
2233                         if (arch == 'x64') {
2234                             buildCommands += "build.cmd ${lowerConfiguration} arm64 linuxmscorlib"
2235                         }
2236
2237                         if (!isJitStressScenario(scenario)) {
2238                             // Zip up the tests directory so that we don't use so much space/time copying
2239                             // 10s of thousands of files around.
2240                             buildCommands += "powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::CreateFromDirectory('.\\bin\\tests\\${osGroup}.${arch}.${configuration}', '.\\bin\\tests\\tests.zip')\"";
2241
2242                             // For Windows, pull full test results and test drops for x86/x64.
2243                             // No need to pull for stress mode scenarios (downstream builds use the default scenario)
2244                             Utilities.addArchival(newJob, "bin/Product/**,bin/tests/tests.zip", "bin/Product/**/.nuget/**")
2245                         }
2246
2247                         if (scenario == 'jitdiff') {
2248                             // retrieve jit-dasm output for base commit, and run jit-diff
2249                             if (!isBuildOnly) {
2250                                 // if this is a build only job, we want to keep the default (build) artifacts for the flow job
2251                                 Utilities.addArchival(newJob, "bin/tests/${osGroup}.${arch}.${configuration}/dasm/**")
2252                             }
2253                         }
2254
2255                         if (!isBuildOnly) {
2256                             Utilities.addXUnitDotNETResults(newJob, 'bin/**/TestRun*.xml', true)
2257                         }
2258                     }
2259                     break
2260                 case 'arm':
2261                 case 'arm64':
2262                     assert isArmWindowsScenario(scenario)
2263
2264                     def buildOpts = ''
2265
2266                     if (buildCoreclrTests) {
2267                         buildOpts += " -priority=${priority}"
2268                     } else {
2269                         buildOpts += ' skiptests'
2270                     }
2271
2272                     // This is now a build only job. Do not run tests. Use the flow job.
2273                     buildCommands += "set __TestIntermediateDir=int&&build.cmd ${lowerConfiguration} ${architecture} ${buildOpts}"
2274
2275                     if (doCoreFxTesting) {
2276                         assert isBuildOnly
2277
2278                         // Set the stress mode variables; this is incorporated into the generated CoreFx RunTests.cmd files.
2279                         def envScriptPath = ''
2280                         def buildCommandsStr = ''
2281                         envScriptPath = "%WORKSPACE%\\SetStressModes.bat"
2282                         buildCommandsStr += envScriptCreate(os, envScriptPath)
2283                         buildCommandsStr += envScriptSetStressModeVariables(os, Constants.jitStressModeScenarios[scenario], envScriptPath)
2284                         envScriptFinalize(os, envScriptPath)
2285                         buildCommands += buildCommandsStr
2286
2287                         def workspaceRelativeFxRootLinux = "_/fx"
2288                         def workspaceRelativeFxRootWin = "_\\fx"
2289                         def absoluteFxRoot = "%WORKSPACE%\\_\\fx"
2290                         def fxBranch = getFxBranch(branch)
2291
2292                         buildCommands += "python -u %WORKSPACE%\\tests\\scripts\\run-corefx-tests.py -arch ${architecture} -ci_arch ${architecture} -build_type ${configuration} -fx_root ${absoluteFxRoot} -fx_branch ${fxBranch} -env_script ${envScriptPath} -no_run_tests"
2293
2294                         // Zip up the CoreFx runtime and tests. We don't need the CoreCLR binaries; they have been copied to the CoreFX tree.
2295                         buildCommands += "powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::CreateFromDirectory('${workspaceRelativeFxRootWin}\\artifacts\\bin\\testhost\\netcoreapp-Windows_NT-Release-${architecture}', '${workspaceRelativeFxRootWin}\\fxruntime.zip')\"";
2296                         buildCommands += "powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::CreateFromDirectory('${workspaceRelativeFxRootWin}\\artifacts\\bin\\tests', '${workspaceRelativeFxRootWin}\\fxtests.zip')\"";
2297
2298                         Utilities.addArchival(newJob, "${workspaceRelativeFxRootLinux}/fxruntime.zip")
2299                         Utilities.addArchival(newJob, "${workspaceRelativeFxRootLinux}/fxtests.zip")
2300                     } else {
2301                         // Zip up the tests directory so that we don't use so much space/time copying
2302                         // 10s of thousands of files around.
2303                         buildCommands += "powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::CreateFromDirectory('.\\bin\\tests\\${osGroup}.${architecture}.${configuration}', '.\\bin\\tests\\tests.zip')\"";
2304
2305                         // Add archival.
2306                         Utilities.addArchival(newJob, "bin/Product/**,bin/tests/tests.zip", "bin/Product/**/.nuget/**")
2307                     }
2308                     break
2309                 default:
2310                     println("Unknown architecture: ${architecture}");
2311                     assert false
2312                     break
2313             }
2314             break
2315         // end case 'Windows_NT'; editor brace matching: }
2316         case 'Ubuntu':
2317         case 'Ubuntu16.04':
2318         case 'Ubuntu16.10':
2319         case 'Debian8.4':
2320         case 'OSX10.12':
2321         case 'CentOS7.1':
2322         case 'RHEL7.2':
2323         case 'Tizen':
2324         case 'Fedora24': // editor brace matching: {
2325             switch (architecture) {
2326                 case 'x86':
2327                     if (os == 'Ubuntu') {
2328                         // build and PAL test
2329                         def dockerImage = getDockerImageName(architecture, os, true)
2330                         buildCommands += "docker run -i --rm -v \${WORKSPACE}:/opt/code -w /opt/code -e ROOTFS_DIR=/crossrootfs/x86 ${dockerImage} ./build.sh ${architecture} cross ${lowerConfiguration}"
2331                         dockerImage = getDockerImageName(architecture, os, false)
2332                         buildCommands += "docker run -i --rm -v \${WORKSPACE}:/opt/code -w /opt/code ${dockerImage} ./src/pal/tests/palsuite/runpaltests.sh /opt/code/bin/obj/${osGroup}.${architecture}.${configuration} /opt/code/bin/paltestout"
2333                         Utilities.addArchival(newJob, "bin/Product/**,bin/obj/*/tests/**/*.so", "bin/Product/**/.nuget/**")
2334                         Utilities.addXUnitDotNETResults(newJob, '**/pal_tests.xml')
2335                     }
2336                     break
2337
2338                 case 'x64':
2339                     if (scenario == 'formatting') {
2340                         buildCommands += "python tests/scripts/format.py -c \${WORKSPACE} -o Linux -a ${architecture}"
2341                         Utilities.addArchival(newJob, "format.patch", "", true, false)
2342                         break
2343                     }
2344
2345                     if (scenario == 'pmi_asm_diffs') {
2346                         buildCommands += "./build.sh ${lowerConfiguration} ${architecture} skiptests skipbuildpackages"
2347                         buildCommands += "./build-test.sh ${lowerConfiguration} ${architecture} generatelayoutonly"
2348
2349                         // TODO: Add -target_branch and -commit_hash arguments based on GitHub variables.
2350                         buildCommands += "python -u \${WORKSPACE}/tests/scripts/run-pmi-diffs.py -arch ${architecture} -ci_arch ${architecture} -build_type ${configuration}"
2351
2352                         // Archive the asm
2353                         buildCommands += "tar -czf dasm.${os}.${architecture}.${configuration}.tgz ./_/pmi/asm"
2354                         Utilities.addArchival(newJob, "dasm.${os}.${architecture}.${configuration}.tgz")
2355                         break
2356                     }
2357
2358                     if (scenario == 'illink') {
2359                         assert(os == 'Ubuntu')
2360                         buildCommands += "./tests/scripts/build_illink.sh --clone --arch=${architecture}"
2361                     }
2362
2363                     if (!doCoreFxTesting) {
2364                         // We run pal tests on all OS but generate mscorlib (and thus, nuget packages)
2365                         // only on supported OS platforms.
2366                         def bootstrapRid = Utilities.getBoostrapPublishRid(os)
2367                         def bootstrapRidEnv = bootstrapRid != null ? "__PUBLISH_RID=${bootstrapRid} " : ''
2368
2369                         buildCommands += "${bootstrapRidEnv}./build.sh ${lowerConfiguration} ${architecture}"
2370
2371                         def testBuildOpts = ""
2372                         if (priority == '1') {
2373                             testBuildOpts = "priority1"
2374                         }
2375
2376                         buildCommands += "./build-test.sh ${lowerConfiguration} ${architecture} ${testBuildOpts}"
2377                         buildCommands += "src/pal/tests/palsuite/runpaltests.sh \${WORKSPACE}/bin/obj/${osGroup}.${architecture}.${configuration} \${WORKSPACE}/bin/paltestout"
2378
2379                         // Archive the bin/tests folder for *_tst jobs
2380                         def testArtifactsTgzFileName = getTestArtifactsTgzFileName(osGroup, architecture, configuration)
2381                         buildCommands += "tar -czf ${testArtifactsTgzFileName} bin/tests/${osGroup}.${architecture}.${configuration}"
2382                         Utilities.addArchival(newJob, "${testArtifactsTgzFileName}", "")
2383                         // And pal tests
2384                         Utilities.addXUnitDotNETResults(newJob, '**/pal_tests.xml')
2385                     }
2386                     else {
2387                         if (scenario == 'corefx_innerloop') {
2388                             assert os == 'Ubuntu' || 'OSX10.12'
2389                             assert architecture == 'x64'
2390
2391                             buildCommands += "./build.sh ${lowerConfiguration} ${architecture} skiptests"
2392                             buildCommands += "./build-test.sh ${lowerConfiguration} ${architecture} generatetesthostonly"
2393                             buildCommands += "./tests/runtest.sh ${lowerConfiguration} --corefxtestsall --testHostDir=\${WORKSPACE}/bin/tests/${osGroup}.${architecture}.${configuration}/testhost/ --coreclr-src=\${WORKSPACE}"
2394                             
2395                             break
2396                             // Archive and process (only) the test results
2397                             Utilities.addArchival(newJob, "bin/Logs/**/testResults.xml")
2398                             Utilities.addXUnitDotNETResults(newJob, "bin/Logs/**/testResults.xml")
2399                         }
2400                         else {
2401                             // Corefx stress testing
2402                             assert os == 'Ubuntu'
2403                             assert architecture == 'x64'
2404                             assert lowerConfiguration == 'checked'
2405                             assert isJitStressScenario(scenario)
2406
2407                             // Build coreclr
2408                             buildCommands += "./build.sh ${lowerConfiguration} ${architecture}"
2409
2410                             def scriptFileName = "\$WORKSPACE/set_stress_test_env.sh"
2411
2412                             def envScriptCmds = envScriptCreate(os, scriptFileName)
2413                             envScriptCmds += envScriptSetStressModeVariables(os, Constants.jitStressModeScenarios[scenario], scriptFileName)
2414                             envScriptCmds += envScriptFinalize(os, scriptFileName)
2415                             buildCommands += envScriptCmds
2416
2417                             // Build and text corefx
2418                             def workspaceRelativeFxRoot = "_/fx"
2419                             def absoluteFxRoot = "\$WORKSPACE/${workspaceRelativeFxRoot}"
2420                             def fxBranch = getFxBranch(branch)
2421
2422                             buildCommands += "python -u \$WORKSPACE/tests/scripts/run-corefx-tests.py -arch ${architecture} -ci_arch ${architecture} -build_type ${configuration} -fx_root ${absoluteFxRoot} -fx_branch ${fxBranch} -env_script ${scriptFileName}"
2423
2424                             // Archive and process (only) the test results
2425                             Utilities.addArchival(newJob, "${workspaceRelativeFxRoot}/artifacts/bin/**/testResults.xml")
2426                             Utilities.addXUnitDotNETResults(newJob, "${workspaceRelativeFxRoot}/artifacts/bin/**/testResults.xml")
2427                         }
2428                     }
2429                     break
2430                 case 'armem':
2431                     // Emulator cross builds for ARM runs on Tizen currently
2432                     assert os == 'Tizen'
2433
2434                     def arm_abi = "armel"
2435                     def linuxCodeName = "tizen"
2436
2437                     // Unzip the Windows test binaries first. Exit with 0
2438                     buildCommands += "unzip -q -o ./bin/tests/tests.zip -d ./bin/tests/Windows_NT.x64.${configuration} || exit 0"
2439
2440                     // Unpack the corefx binaries
2441                     buildCommands += "mkdir ./bin/CoreFxBinDir"
2442                     buildCommands += "tar -xf ./artifacts/bin/build.tar.gz -C ./bin/CoreFxBinDir"
2443
2444                     // Call the ARM CI script to cross build and test using docker
2445                     buildCommands += """./tests/scripts/arm32_ci_script.sh \\
2446                     --mode=docker \\
2447                     --${arm_abi} \\
2448                     --linuxCodeName=${linuxCodeName} \\
2449                     --buildConfig=${lowerConfiguration} \\
2450                     --testRootDir=./bin/tests/Windows_NT.x64.${configuration} \\
2451                     --coreFxBinDir=./bin/CoreFxBinDir \\
2452                     --testDirFile=./tests/testsRunningInsideARM.txt"""
2453
2454                     // Basic archiving of the build, no pal tests
2455                     Utilities.addArchival(newJob, "bin/Product/**,bin/obj/*/tests/**/*.dylib,bin/obj/*/tests/**/*.so", "bin/Product/**/.nuget/**")
2456                     break
2457                 case 'arm64':
2458                 case 'arm':
2459                     // Non-Windows ARM cross builds on hardware run on Ubuntu only
2460                     assert (os == 'Ubuntu') || (os == 'Ubuntu16.04')
2461
2462                     // Add some useful information to the log file. Ignore return codes.
2463                     buildCommands += "uname -a || true"
2464
2465                     // Cross build the Ubuntu/arm product using docker with a docker image that contains the correct
2466                     // Ubuntu cross-compilation toolset (running on a Ubuntu x64 host).
2467                     // For CoreFX testing, we only need the product build; we don't need to generate the layouts. The product
2468                     // build is then copied into the corefx layout by the run-corefx-test.py script. For CoreFX testing, we
2469                     // ZIP up the generated CoreFX runtime and tests.
2470
2471                     def dockerImage = getDockerImageName(architecture, os, true)
2472                     def dockerCmd = "docker run -i --rm -v \${WORKSPACE}:\${WORKSPACE} -w \${WORKSPACE} -e ROOTFS_DIR=/crossrootfs/${architecture} ${dockerImage} "
2473
2474                     buildCommands += "${dockerCmd}\${WORKSPACE}/build.sh ${lowerConfiguration} ${architecture} cross"
2475
2476                     if (doCoreFxTesting) {
2477                         def scriptFileName = "\$WORKSPACE/set_stress_test_env.sh"
2478
2479                         def envScriptCmds = envScriptCreate(os, scriptFileName)
2480                         envScriptCmds += envScriptSetStressModeVariables(os, Constants.jitStressModeScenarios[scenario], scriptFileName)
2481                         envScriptCmds += envScriptFinalize(os, scriptFileName)
2482                         buildCommands += envScriptCmds
2483
2484                         // Build and text corefx
2485                         def workspaceRelativeFxRootLinux = "_/fx"
2486                         def absoluteFxRoot = "\$WORKSPACE/${workspaceRelativeFxRootLinux}"
2487                         def fxBranch = getFxBranch(branch)
2488
2489                         buildCommands += "${dockerCmd}python -u \$WORKSPACE/tests/scripts/run-corefx-tests.py -arch ${architecture} -ci_arch ${architecture} -build_type ${configuration} -fx_root ${absoluteFxRoot} -fx_branch ${fxBranch} -env_script ${scriptFileName} -no_run_tests"
2490
2491                         // Docker creates files with root permission, so we need to zip in docker also, or else we'll get permission errors.
2492                         buildCommands += "${dockerCmd}zip -r ${workspaceRelativeFxRootLinux}/fxruntime.zip ${workspaceRelativeFxRootLinux}/artifacts/bin/testhost/netcoreapp-Linux-Release-${architecture}"
2493                         buildCommands += "${dockerCmd}zip -r ${workspaceRelativeFxRootLinux}/fxtests.zip ${workspaceRelativeFxRootLinux}/artifacts/bin/tests"
2494
2495                         Utilities.addArchival(newJob, "${workspaceRelativeFxRootLinux}/fxruntime.zip")
2496                         Utilities.addArchival(newJob, "${workspaceRelativeFxRootLinux}/fxtests.zip")
2497                     }
2498                     else if (isCrossGenComparisonScenario(scenario)) {
2499                         buildCommands += "${dockerCmd}\${WORKSPACE}/build-test.sh ${lowerConfiguration} ${architecture} cross generatelayoutonly"
2500
2501                         def workspaceRelativeProductBinDir = "bin/Product/${osGroup}.${architecture}.${configuration}"
2502                         def workspaceRelativeCoreLib = "${workspaceRelativeProductBinDir}/IL/System.Private.CoreLib.dll"
2503                         def workspaceRelativeCoreRootDir = "bin/tests/${osGroup}.${architecture}.${configuration}/Tests/Core_Root"
2504                         def workspaceRelativeCrossGenComparisonScript = "tests/scripts/crossgen_comparison.py"
2505                         def workspaceRelativeResultsDir = "_"
2506                         def workspaceRelativeArtifactsArchive = "${os}.${architecture}.${configuration}.${scenario}.zip"
2507                         def crossGenComparisonCmd = "python -u \${WORKSPACE}/${workspaceRelativeCrossGenComparisonScript} "
2508                         def crossArch = "x64"
2509                         def crossGenExecutable = "\${WORKSPACE}/${workspaceRelativeProductBinDir}/${crossArch}/crossgen"
2510                         def workspaceRelativeCrossArchResultDir = "${workspaceRelativeResultsDir}/${osGroup}.${crossArch}_${architecture}.${configuration}"
2511
2512                         buildCommands += "${dockerCmd}mkdir -p \${WORKSPACE}/${workspaceRelativeCrossArchResultDir}"
2513                         buildCommands += "${dockerCmd}${crossGenComparisonCmd}crossgen_corelib --crossgen ${crossGenExecutable} --il_corelib \${WORKSPACE}/${workspaceRelativeCoreLib} --result_dir \${WORKSPACE}/${workspaceRelativeCrossArchResultDir}"
2514                         buildCommands += "${dockerCmd}${crossGenComparisonCmd}crossgen_framework --crossgen ${crossGenExecutable} --core_root \${WORKSPACE}/${workspaceRelativeCoreRootDir} --result_dir \${WORKSPACE}/${workspaceRelativeCrossArchResultDir}"
2515
2516                         buildCommands += "${dockerCmd}zip -r ${workspaceRelativeArtifactsArchive} ${workspaceRelativeCoreLib} ${workspaceRelativeCoreRootDir} ${workspaceRelativeCrossGenComparisonScript} ${workspaceRelativeResultsDir}"
2517                         Utilities.addArchival(newJob, "${workspaceRelativeArtifactsArchive}")
2518                     }
2519                     else if (scenario == 'pmi_asm_diffs') {
2520                         buildCommands += "${dockerCmd}\${WORKSPACE}/build-test.sh ${lowerConfiguration} ${architecture} cross generatelayoutonly"
2521
2522                         // Pass `--skip_diffs` -- the actual diffs will be done on an arm machine in the test job. This is the build job.
2523                         // TODO: Add -target_branch and -commit_hash arguments based on GitHub variables.
2524                         buildCommands += "python -u \${WORKSPACE}/tests/scripts/run-pmi-diffs.py -arch ${architecture} -ci_arch ${architecture} -build_type ${configuration} --skip_diffs"
2525
2526                         // ZIP what we created.
2527                         buildCommands += "zip -r product.${os}.${architecture}.${lowerConfiguration}.zip ./bin/Product/Linux.${architecture}.${configuration}"
2528                         buildCommands += "zip -r product.baseline.${os}.${architecture}.${lowerConfiguration}.zip ./_/pmi/base/bin/Product/Linux.${architecture}.${configuration}"
2529                         buildCommands += "zip -r coreroot.${os}.${architecture}.${lowerConfiguration}.zip ./bin/tests/Linux.${architecture}.${configuration}/Tests/Core_Root"
2530                         buildCommands += "zip -r coreroot.baseline.${os}.${architecture}.${lowerConfiguration}.zip ./_/pmi/base/bin/tests/Linux.${architecture}.${configuration}/Tests/Core_Root"
2531
2532                         // Archive the built artifacts
2533                         Utilities.addArchival(newJob, "product.${os}.${architecture}.${lowerConfiguration}.zip,product.baseline.${os}.${architecture}.${lowerConfiguration}.zip,coreroot.${os}.${architecture}.${lowerConfiguration}.zip,coreroot.baseline.${os}.${architecture}.${lowerConfiguration}.zip")
2534                     }
2535                     else {
2536                         // Then, using the same docker image, build the tests and generate the CORE_ROOT layout.
2537
2538                         def testBuildOpts = ""
2539                         if (priority == '1') {
2540                             testBuildOpts = "priority1"
2541                         }
2542
2543                         buildCommands += "${dockerCmd}\${WORKSPACE}/build-test.sh ${lowerConfiguration} ${architecture} cross ${testBuildOpts}"
2544
2545                         // ZIP up the built tests (including CORE_ROOT and native test components copied to the CORE_ROOT) for the test job (created in the flow job code)
2546                         def testArtifactsTgzFileName = getTestArtifactsTgzFileName(osGroup, architecture, configuration)
2547                         buildCommands += "tar -czf ${testArtifactsTgzFileName} bin/tests/${osGroup}.${architecture}.${configuration}"
2548
2549                         Utilities.addArchival(newJob, "${testArtifactsTgzFileName}", "")
2550                     }
2551
2552                     // Archive the build logs from both product and test builds.
2553                     Utilities.addArchival(newJob, "bin/Logs/*.log,bin/Logs/*.wrn,bin/Logs/*.err", "")
2554
2555                     // We need to clean up the build machines; the docker build leaves newly built files with root permission, which
2556                     // the cleanup task in Jenkins can't remove.
2557                     newJob.with {
2558                         publishers {
2559                             azureVMAgentPostBuildAction {
2560                                 agentPostBuildAction('Delete agent after build execution (when idle).')
2561                             }
2562                         }
2563                     }
2564                     break
2565                 default:
2566                     println("Unknown architecture: ${architecture}");
2567                     assert false
2568                     break
2569             }
2570             break
2571         // editor brace matching: }
2572         default:
2573             println("Unknown os: ${os}");
2574             assert false
2575             break
2576     } // os
2577
2578     return buildCommands
2579 }
2580
2581 // Determine if we should generate a job for the given parameters. This is for non-flow jobs: either build and test, or build only.
2582 // Returns true if the job should be generated.
2583 def static shouldGenerateJob(def scenario, def isPR, def architecture, def configuration, def os, def isBuildOnly)
2584 {
2585     // The various "innerloop" jobs are only available as PR triggered.
2586
2587     if (!isPR) {
2588         if (isInnerloopTestScenario(scenario)) {
2589             return false
2590         }
2591
2592         if (scenario == 'corefx_innerloop') {
2593             return false
2594         }
2595     }
2596
2597     // Tizen is only supported for armem architecture
2598     if (os == 'Tizen' && architecture != 'armem') {
2599         return false
2600     }
2601
2602     // Filter based on architecture.
2603
2604     switch (architecture) {
2605         case 'arm':
2606             if ((os != 'Windows_NT') && (os != 'Ubuntu')) {
2607                 return false
2608             }
2609             break
2610         case 'arm64':
2611             if ((os != 'Windows_NT') && (os != 'Ubuntu16.04')) {
2612                 return false
2613             }
2614             break
2615         case 'armem':
2616             if (os != 'Tizen') {
2617                 return false
2618             }
2619             break
2620         case 'x86':
2621             if ((os != 'Windows_NT') && (os != 'Ubuntu')) {
2622                 return false
2623             }
2624             break
2625         case 'x64':
2626             // Everything implemented
2627             break
2628         default:
2629             println("Unknown architecture: ${architecture}")
2630             assert false
2631             break
2632     }
2633
2634     // Which (Windows) build only jobs are required?
2635
2636     def isNormalOrInnerloop = (scenario == 'innerloop' || scenario == 'normal')
2637
2638     if (isBuildOnly) {
2639         switch (architecture) {
2640             case 'arm':
2641             case 'arm64':
2642                 // We use build only jobs for Windows arm/arm64 cross-compilation corefx testing, so we need to generate builds for that.
2643                 if (!isCoreFxScenario(scenario)) {
2644                     return false
2645                 }
2646                 break
2647             case 'x64':
2648             case 'x86':
2649                 if (!isNormalOrInnerloop) {
2650                     return false
2651                 }
2652                 break
2653             default:
2654                 return false
2655         }
2656     }
2657
2658     // Filter based on scenario.
2659
2660     if (isJitStressScenario(scenario)) {
2661         if (configuration != 'Checked') {
2662             return false
2663         }
2664
2665         def isEnabledOS = (os == 'Windows_NT') ||
2666                           (os == 'Ubuntu' && (architecture == 'x64') && isCoreFxScenario(scenario)) ||
2667                           (os == 'Ubuntu' && architecture == 'arm') ||
2668                           (os == 'Ubuntu16.04' && architecture == 'arm64')
2669         if (!isEnabledOS) {
2670             return false
2671         }
2672
2673         switch (architecture) {
2674             case 'x64':
2675                 break
2676
2677             case 'x86':
2678                 // x86 ubuntu: no stress modes
2679                 if (os == 'Ubuntu') {
2680                     return false
2681                 }
2682                 break
2683
2684             case 'arm':
2685             case 'arm64':
2686                 // We use build only jobs for Windows arm/arm64 cross-compilation corefx testing, so we need to generate builds for that.
2687                 // No "regular" Windows arm corefx jobs, e.g.
2688                 // For Ubuntu arm corefx testing, we use regular jobs (not "build only" since only Windows has "build only", and
2689                 // the Ubuntu arm "regular" jobs don't run tests anyway).
2690                 if (os == 'Windows_NT') {
2691                     if (! (isBuildOnly && isCoreFxScenario(scenario)) ) {
2692                         return false
2693                     }
2694                 }
2695                 else {
2696                     if (!isCoreFxScenario(scenario)) {
2697                         return false
2698                     }
2699                 }
2700                 break
2701
2702             default:
2703                 // armem: no stress jobs for ARM emulator.
2704                 return false
2705         }
2706     }
2707     else if (isR2RScenario(scenario)) {
2708         if (os != 'Windows_NT') {
2709             return false
2710         }
2711
2712         if (isR2RBaselineScenario(scenario)) {
2713             // no need for Debug scenario; Checked is sufficient
2714             if (configuration != 'Checked' && configuration != 'Release') {
2715                 return false
2716             }
2717         }
2718         else if (isR2RStressScenario(scenario)) {
2719             // Stress scenarios only run with Checked builds, not Release (they would work with Debug, but be slow).
2720             if (configuration != 'Checked') {
2721                 return false
2722             }
2723         }
2724
2725         switch (architecture) {
2726             case 'arm':
2727             case 'arm64':
2728                 // Windows arm/arm64 ready-to-run jobs use flow jobs and test jobs, but depend on "normal" (not R2R specific) build jobs.
2729                 return false
2730
2731             default:
2732                 break
2733         }
2734     }
2735     else if (isCrossGenComparisonScenario(scenario)) {
2736         return shouldGenerateCrossGenComparisonJob(os, architecture, configuration, scenario)
2737     }
2738     else {
2739         // Skip scenarios
2740         switch (scenario) {
2741             case 'ilrt':
2742                 // The ilrt build isn't necessary except for Windows_NT2003.  Non-Windows NT uses
2743                 // the default scenario build
2744                 if (os != 'Windows_NT') {
2745                     return false
2746                 }
2747                 // Only x64 for now
2748                 if (architecture != 'x64') {
2749                     return false
2750                 }
2751                 // Release only
2752                 if (configuration != 'Release') {
2753                     return false
2754                 }
2755                 break
2756             case 'jitdiff':
2757                 if (os != 'Windows_NT' && os != 'Ubuntu' && os != 'OSX10.12') {
2758                     return false
2759                 }
2760                 if (architecture != 'x64') {
2761                     return false
2762                 }
2763                 if (configuration != 'Checked') {
2764                     return false
2765                 }
2766                 break
2767             case 'longgc':
2768             case 'gcsimulator':
2769                 if (os != 'Windows_NT' && os != 'Ubuntu' && os != 'OSX10.12') {
2770                     return false
2771                 }
2772                 if (architecture != 'x64') {
2773                     return false
2774                 }
2775                 if (configuration != 'Release') {
2776                     return false
2777                 }
2778                 break
2779             case 'gc_reliability_framework':
2780             case 'standalone_gc':
2781                 if (os != 'Windows_NT' && os != 'Ubuntu' && os != 'OSX10.12') {
2782                     return false
2783                 }
2784
2785                 if (architecture != 'x64') {
2786                     return false
2787                 }
2788
2789                 if (configuration != 'Release' && configuration != 'Checked') {
2790                     return false
2791                 }
2792                 break
2793             // We only run Windows and Ubuntu x64 Checked for formatting right now
2794             case 'formatting':
2795                 if (os != 'Windows_NT' && os != 'Ubuntu') {
2796                     return false
2797                 }
2798                 if (architecture != 'x64') {
2799                     return false
2800                 }
2801                 if (configuration != 'Checked') {
2802                     return false
2803                 }
2804                 break
2805             case 'illink':
2806                 if (os != 'Windows_NT' && (os != 'Ubuntu' || architecture != 'x64')) {
2807                     return false
2808                 }
2809                 if (architecture != 'x64' && architecture != 'x86') {
2810                     return false
2811                 }
2812                 break
2813             case 'normal':
2814                 // Nothing skipped
2815                 break
2816             case 'innerloop':
2817                 if (!isValidPrTriggeredInnerLoopJob(os, architecture, configuration, isBuildOnly)) {
2818                     return false
2819                 }
2820                 break
2821             case 'corefx_innerloop':
2822                 if (os != 'Windows_NT' && os != 'Ubuntu' &&  os != 'OSX10.12') {
2823                     return false
2824                 }
2825                 if (architecture != 'x64') {
2826                     return false
2827                 }
2828                 break
2829             case 'pmi_asm_diffs':
2830                 if (configuration != 'Checked') {
2831                     return false
2832                 }
2833                 if (architecture == 'armem') {
2834                     return false
2835                 }
2836                 // Currently, we don't support pmi_asm_diffs for Windows arm/arm64. We don't have a dotnet CLI available to
2837                 // build jitutils. The jobs are not in validArmWindowsScenarios.
2838                 if ((os == 'Windows_NT') && (architecture == 'arm' || architecture == 'arm64')) {
2839                     return false
2840                 }
2841                 // Currently, no support for Linux x86.
2842                 if ((os != 'Windows_NT') && (architecture == 'x86')) {
2843                     return false
2844                 }
2845                 break
2846             default:
2847                 println("Unknown scenario: ${scenario}")
2848                 assert false
2849                 break
2850         }
2851     }
2852
2853     // The job was not filtered out, so we should generate it!
2854     return true
2855 }
2856
2857 Constants.allScenarios.each { scenario ->
2858     [true, false].each { isPR ->
2859         Constants.architectureList.each { architecture ->
2860             Constants.configurationList.each { configuration ->
2861                 Constants.osList.each { os ->
2862                     // If the OS is Windows_NT_BuildOnly, set the isBuildOnly flag to true
2863                     // and reset the os to Windows_NT
2864                     def isBuildOnly = false
2865                     if (os == 'Windows_NT_BuildOnly') {
2866                         isBuildOnly = true
2867                         os = 'Windows_NT'
2868                     }
2869
2870                     if (!shouldGenerateJob(scenario, isPR, architecture, configuration, os, isBuildOnly)) {
2871                         return
2872                     }
2873
2874                     // Calculate names
2875                     def jobName = getJobName(configuration, architecture, os, scenario, isBuildOnly)
2876                     def folderName = getJobFolder(scenario)
2877
2878                     // Create the new job
2879                     def newJob = job(Utilities.getFullJobName(project, jobName, isPR, folderName)) {}
2880
2881                     addToViews(newJob, false, isPR, architecture, os, configuration, scenario) // isFlowJob == false
2882
2883                     setJobMachineAffinity(architecture, os, true, false, false, newJob) // isBuildJob = true, isTestJob = false, isFlowJob = false
2884
2885                     Utilities.standardJobSetup(newJob, project, isPR, "*/${branch}")
2886                     addTriggers(newJob, branch, isPR, architecture, os, configuration, scenario, false, isBuildOnly) // isFlowJob==false
2887                     setJobTimeout(newJob, isPR, architecture, configuration, scenario, isBuildOnly)
2888
2889                     // Copy Windows build test binaries and corefx build artifacts for Linux cross build for armem.
2890                     // We don't use a flow job for this, but we do depend on there being existing builds with these
2891                     // artifacts produced.
2892                     if ((architecture == 'armem') && (os == 'Tizen')) {
2893                         // Define the Windows Tests and Corefx build job names
2894                         def lowerConfiguration = configuration.toLowerCase()
2895                         def WindowsTestsName = projectFolder + '/' +
2896                                                Utilities.getFullJobName(project,
2897                                                                         getJobName(lowerConfiguration, 'x64' , 'windows_nt', 'normal', true),
2898                                                                         false)
2899                         def fxBranch = getFxBranch(branch)
2900                         def corefxFolder = Utilities.getFolderName('dotnet/corefx') + '/' +
2901                                            Utilities.getFolderName(fxBranch)
2902
2903                         def arm_abi = 'armel'
2904                         def corefx_os = 'tizen'
2905
2906                         // Let's use release CoreFX to test checked CoreCLR,
2907                         // because we do not generate checked CoreFX in CoreFX CI yet.
2908                         def corefx_lowerConfiguration = lowerConfiguration
2909                         if (lowerConfiguration == 'checked') {
2910                             corefx_lowerConfiguration = 'release'
2911                         }
2912
2913                         // Copy the Windows test binaries and the Corefx build binaries
2914                         newJob.with {
2915                             steps {
2916                                 copyArtifacts(WindowsTestsName) {
2917                                     includePatterns('bin/tests/tests.zip')
2918                                     buildSelector {
2919                                         latestSuccessful(true)
2920                                     }
2921                                 }
2922                                 copyArtifacts("${corefxFolder}/${corefx_os}_${arm_abi}_cross_${corefx_lowerConfiguration}") {
2923                                     includePatterns('artifacts/bin/build.tar.gz')
2924                                     buildSelector {
2925                                         latestSuccessful(true)
2926                                     }
2927                                 }
2928                             } // steps
2929                         } // newJob.with
2930                     }
2931
2932                     def buildCommands = calculateBuildCommands(newJob, scenario, branch, isPR, architecture, configuration, os, isBuildOnly)
2933
2934                     newJob.with {
2935                         steps {
2936                             if (os == 'Windows_NT') {
2937                                 buildCommands.each { buildCommand ->
2938                                     batchFile(buildCommand)
2939                                 }
2940                             }
2941                             else {
2942                                 buildCommands.each { buildCommand ->
2943                                     shell(buildCommand)
2944                                 }
2945                             }
2946                         } // steps
2947                     } // newJob.with
2948
2949                 } // os
2950             } // configuration
2951         } // architecture
2952     } // isPR
2953 } // scenario
2954
2955 // Create a Windows ARM/ARM64 test job that will be used by a flow job.
2956 // Returns the newly created job.
2957 def static CreateWindowsArmTestJob(def dslFactory, def project, def architecture, def os, def configuration, def scenario, def isPR, def inputCoreCLRBuildName)
2958 {
2959     def osGroup = getOSGroup(os)
2960     def jobName = getJobName(configuration, architecture, os, scenario, false) + "_tst"
2961
2962     def jobFolder = getJobFolder(scenario)
2963     def newJob = dslFactory.job(Utilities.getFullJobName(project, jobName, isPR, jobFolder)) {
2964         parameters {
2965             stringParam('CORECLR_BUILD', '', "Build number to copy CoreCLR ${osGroup} binaries from")
2966         }
2967
2968         steps {
2969             // Set up the copies
2970
2971             // Coreclr build we are trying to test
2972             //
2973             //  ** NOTE ** This will, correctly, overwrite the CORE_ROOT from the Windows test archive
2974
2975             copyArtifacts(inputCoreCLRBuildName) {
2976                 excludePatterns('**/testResults.xml', '**/*.ni.dll')
2977                 buildSelector {
2978                     buildNumber('${CORECLR_BUILD}')
2979                 }
2980             }
2981
2982             if (isCoreFxScenario(scenario)) {
2983
2984                 // Only arm/arm64 supported for corefx testing now.
2985                 assert architecture == 'arm' || architecture == 'arm64'
2986
2987                 // Unzip CoreFx runtime
2988                 batchFile("powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::ExtractToDirectory('_\\fx\\fxruntime.zip', '_\\fx\\artifacts\\bin\\testhost\\netcoreapp-Windows_NT-Release-${architecture}')\"")
2989
2990                 // Unzip CoreFx tests.
2991                 batchFile("powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::ExtractToDirectory('_\\fx\\fxtests.zip', '_\\fx\\artifacts\\bin\\tests')\"")
2992
2993                 // Add the script to run the corefx tests
2994                 def corefx_runtime_path   = "%WORKSPACE%\\_\\fx\\artifacts\\bin\\testhost\\netcoreapp-Windows_NT-Release-${architecture}"
2995                 def corefx_tests_dir      = "%WORKSPACE%\\_\\fx\\artifacts\\bin\\tests"
2996                 def corefx_exclusion_file = "%WORKSPACE%\\tests\\${architecture}\\corefx_test_exclusions.txt"
2997                 batchFile("call %WORKSPACE%\\tests\\scripts\\run-corefx-tests.bat ${corefx_runtime_path} ${corefx_tests_dir} ${corefx_exclusion_file} ${architecture}")
2998
2999             } else { // !isCoreFxScenario(scenario)
3000
3001                 // Unzip tests.
3002                 batchFile("powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::ExtractToDirectory('bin\\tests\\tests.zip', 'bin\\tests\\${osGroup}.${architecture}.${configuration}')\"")
3003
3004                 def buildCommands = ""
3005
3006                 def coreRootLocation = "%WORKSPACE%\\bin\\tests\\Windows_NT.${architecture}.${configuration}\\Tests\\Core_Root"
3007                 def addEnvVariable =  { variable, value -> buildCommands += "set ${variable}=${value}\r\n"}
3008                 def addCommand = { cmd -> buildCommands += "${cmd}\r\n"}
3009
3010                 // Make sure Command Extensions are enabled. Used so %ERRORLEVEL% is available.
3011                 addCommand("SETLOCAL ENABLEEXTENSIONS")
3012
3013                 // For all jobs 
3014                 addEnvVariable("CORE_ROOT", coreRootLocation)
3015                 addEnvVariable("COMPlus_NoGuiOnAssert", "1")
3016                 addEnvVariable("COMPlus_ContinueOnAssert", "0")
3017
3018                 // If we are running a stress mode, we'll set those variables as well
3019                 if (isJitStressScenario(scenario) || isR2RStressScenario(scenario)) {
3020                     def stressValues = null
3021                     if (isJitStressScenario(scenario)) {
3022                         stressValues = Constants.jitStressModeScenarios[scenario]
3023                     }
3024                     else {
3025                         stressValues = Constants.r2rStressScenarios[scenario]
3026                     }
3027
3028                     stressValues.each { key, value -> 
3029                         addEnvVariable(key, value)
3030                     }
3031                 }
3032
3033                 if (isR2RScenario(scenario)) {
3034                     // Crossgen the framework assemblies.
3035                     buildCommands += """
3036 @for %%F in (%CORE_ROOT%\\*.dll) do @call :PrecompileAssembly "%CORE_ROOT%" "%%F" %%~nxF
3037 @goto skip_PrecompileAssembly
3038
3039 :PrecompileAssembly
3040 @REM Skip mscorlib since it is already precompiled.
3041 @if /I "%3" == "mscorlib.dll" exit /b 0
3042 @if /I "%3" == "mscorlib.ni.dll" exit /b 0
3043
3044 "%CORE_ROOT%\\crossgen.exe" /Platform_Assemblies_Paths "%CORE_ROOT%" %2 >nul 2>nul
3045 @if "%errorlevel%" == "-2146230517" (
3046     echo %2 is not a managed assembly.
3047 ) else if "%errorlevel%" == "-2146234344" (
3048     echo %2 is not a managed assembly.
3049 ) else if %errorlevel% neq 0 (
3050     echo Unable to precompile %2
3051 ) else (
3052     echo Precompiled %2
3053 )
3054 @exit /b 0
3055
3056 :skip_PrecompileAssembly
3057 """
3058
3059                     // Set RunCrossGen variable to cause test wrappers to invoke their logic to run
3060                     // crossgen on tests before running them.
3061                     addEnvVariable("RunCrossGen", "true")
3062                 } // isR2RScenario(scenario)
3063
3064                 // Run runtest.cmd
3065                 // Do not run generate layout. It will delete the correct CORE_ROOT, and we do not have a correct product
3066                 // dir to copy from.
3067                 def runtestCommand = "call %WORKSPACE%\\tests\\runtest.cmd ${architecture} ${configuration} skipgeneratelayout"
3068
3069                 addCommand("${runtestCommand}")
3070                 addCommand("echo on") // Show the following commands in the log. "echo" doesn't alter the errorlevel.
3071                 addCommand("set saved_errorlevel=%errorlevel%")
3072
3073                 // Collect the test logs collected by xunit. Ignore errors here. We want to collect these even if the run
3074                 // failed for some reason, so it needs to be in this batch file.
3075
3076                 addCommand("powershell -NoProfile -Command \"Add-Type -Assembly 'System.IO.Compression.FileSystem'; [System.IO.Compression.ZipFile]::CreateFromDirectory('.\\bin\\tests\\${osGroup}.${architecture}.${configuration}\\Reports', '.\\bin\\tests\\testReports.zip')\"");
3077
3078                 // Use the runtest.cmd errorlevel as the script errorlevel.
3079                 addCommand("exit /b %saved_errorlevel%")
3080
3081                 batchFile(buildCommands)
3082             } // non-corefx testing
3083         } // steps
3084     } // job
3085
3086     if (!isCoreFxScenario(scenario)) {
3087         def doNotFailIfNothingArchived = true
3088         def archiveOnlyIfSuccessful = false
3089         Utilities.addArchival(newJob, "bin/tests/testReports.zip", "", doNotFailIfNothingArchived, archiveOnlyIfSuccessful)
3090
3091         Utilities.addXUnitDotNETResults(newJob, 'bin/**/TestRun*.xml', true)
3092     }
3093
3094     return newJob
3095 }
3096
3097 // Create a test job not covered by the "Windows ARM" case that will be used by a flow job.
3098 // E.g., non-Windows tests.
3099 // Returns the newly created job.
3100 def static CreateOtherTestJob(def dslFactory, def project, def branch, def architecture, def os, def configuration, def scenario, def isPR, def inputCoreCLRBuildName)
3101 {
3102     def lowerConfiguration = configuration.toLowerCase()
3103
3104     def isUbuntuArm64Job = ((os == "Ubuntu16.04") && (architecture == 'arm64'))
3105     def isUbuntuArm32Job = ((os == "Ubuntu") && (architecture == 'arm'))
3106     def isUbuntuArmJob = isUbuntuArm32Job || isUbuntuArm64Job
3107
3108     def doCoreFxTesting = isCoreFxScenario(scenario)
3109     def isPmiAsmDiffsScenario = (scenario == 'pmi_asm_diffs')
3110
3111     def workspaceRelativeFxRootLinux = "_/fx" // only used for CoreFX testing
3112
3113     def osGroup = getOSGroup(os)
3114     def jobName = getJobName(configuration, architecture, os, scenario, false) + "_tst"
3115
3116     def testOpts = ''
3117     def useServerGC = false
3118
3119     // Enable Server GC for Ubuntu PR builds
3120     // REVIEW: why? Does this apply to all architectures? Why only PR?
3121     if (os == 'Ubuntu' && isPR) {
3122         testOpts += ' --useServerGC'
3123         useServerGC = true
3124     }
3125
3126     if (isR2RScenario(scenario)) {
3127
3128         testOpts += ' --crossgen --runcrossgentests'
3129
3130         if (scenario == 'r2r_jitstress1') {
3131             testOpts += ' --jitstress=1'
3132         }
3133         else if (scenario == 'r2r_jitstress2') {
3134             testOpts += ' --jitstress=2'
3135         }
3136         else if (scenario == 'r2r_jitstress1_tiered') {
3137             testOpts += ' --jitstress=1'
3138         }
3139         else if (scenario == 'r2r_jitstress2_tiered') {
3140             testOpts += ' --jitstress=2'
3141         }
3142         else if (scenario == 'r2r_jitstressregs1') {
3143             testOpts += ' --jitstressregs=1'
3144         }
3145         else if (scenario == 'r2r_jitstressregs2') {
3146             testOpts += ' --jitstressregs=2'
3147         }
3148         else if (scenario == 'r2r_jitstressregs3') {
3149             testOpts += ' --jitstressregs=3'
3150         }
3151         else if (scenario == 'r2r_jitstressregs4') {
3152             testOpts += ' --jitstressregs=4'
3153         }
3154         else if (scenario == 'r2r_jitstressregs8') {
3155             testOpts += ' --jitstressregs=8'
3156         }
3157         else if (scenario == 'r2r_jitstressregs0x10') {
3158             testOpts += ' --jitstressregs=0x10'
3159         }
3160         else if (scenario == 'r2r_jitstressregs0x80') {
3161             testOpts += ' --jitstressregs=0x80'
3162         }
3163         else if (scenario == 'r2r_jitstressregs0x1000') {
3164             testOpts += ' --jitstressregs=0x1000'
3165         }
3166         else if (scenario == 'r2r_jitminopts') {
3167             testOpts += ' --jitminopts'
3168         }
3169         else if (scenario == 'r2r_jitforcerelocs') {
3170             testOpts += ' --jitforcerelocs'
3171         }
3172         else if (scenario == 'r2r_gcstress15') {
3173             testOpts += ' --gcstresslevel=0xF'
3174         }
3175     }
3176     else if (scenario == 'jitdiff') {
3177         testOpts += ' --jitdisasm --crossgen'
3178     }
3179     else if (scenario == 'illink') {
3180         testOpts += ' --link=\$WORKSPACE/linker/linker/bin/netcore_Release/netcoreapp2.0/ubuntu-x64/publish/illink'
3181     }
3182     else if (isLongGc(scenario)) {
3183         // Long GC tests behave very poorly when they are not
3184         // the only test running (many of them allocate until OOM).
3185         testOpts += ' --sequential'
3186
3187         // A note - runtest.sh does have "--long-gc" and "--gcsimulator" options
3188         // for running long GC and GCSimulator tests, respectively. We don't use them
3189         // here because using a playlist file produces much more readable output on the CI machines
3190         // and reduces running time.
3191         //
3192         // The Long GC playlist contains all of the tests that are
3193         // going to be run. The GCSimulator playlist contains all of
3194         // the GC simulator tests.
3195         if (scenario == 'longgc') {
3196             testOpts += ' --long-gc --playlist=./tests/longRunningGcTests.txt'
3197         }
3198         else if (scenario == 'gcsimulator') {
3199             testOpts += ' --gcsimulator --playlist=./tests/gcSimulatorTests.txt'
3200         }
3201     }
3202     else if (isGcReliabilityFramework(scenario)) {
3203         testOpts += ' --build-overlay-only'
3204     }
3205     else if (scenario == 'standalone_gc') {
3206         if (osGroup == 'OSX') {
3207             testOpts += ' --gcname=libclrgc.dylib'
3208         }
3209         else if (osGroup == 'Linux') {
3210             testOpts += ' --gcname=libclrgc.so'
3211         }
3212         else {
3213             println("Unexpected OS group: ${osGroup} for os ${os}")
3214             assert false
3215         }
3216     }
3217
3218     def jobFolder = getJobFolder(scenario)
3219     def newJob = dslFactory.job(Utilities.getFullJobName(project, jobName, isPR, jobFolder)) {
3220         parameters {
3221             stringParam('CORECLR_BUILD', '', "Build number to copy CoreCLR ${osGroup} binaries from")
3222         }
3223
3224         steps {
3225             // Set up the copies
3226
3227             // Coreclr build we are trying to test
3228             //
3229             // HACK: the Ubuntu arm64 copyArtifacts Jenkins plug-in is ridiculously slow (45 minutes to
3230             // 1.5 hours for this step). Instead, directly use wget, which is fast (1 minute).
3231
3232             if (!isUbuntuArm64Job) {
3233                 copyArtifacts(inputCoreCLRBuildName) {
3234                     excludePatterns('**/testResults.xml', '**/*.ni.dll')
3235                     buildSelector {
3236                         buildNumber('${CORECLR_BUILD}')
3237                     }
3238                 }
3239             }
3240
3241             if (isUbuntuArmJob) {
3242                 // Add some useful information to the log file. Ignore return codes.
3243                 shell("uname -a || true")
3244             }
3245
3246             if (isUbuntuArm64Job) {
3247                 // Copy the required artifacts directly, using wget, e.g.:
3248                 // 
3249                 //  https://ci.dot.net/job/dotnet_coreclr/job/master/job/arm64_cross_checked_ubuntu16.04_innerloop_prtest/16/artifact/testnativebin.checked.zip
3250                 //  https://ci.dot.net/job/dotnet_coreclr/job/master/job/arm64_cross_checked_ubuntu16.04_innerloop_prtest/16/artifact/tests.checked.zip
3251                 // 
3252                 // parameterized as:
3253                 //
3254                 //  https://ci.dot.net/job/${mungedProjectName}/job/${mungedBranchName}/job/${inputJobName}/${CORECLR_BUILD}/artifact/testnativebin.checked.zip
3255                 //  https://ci.dot.net/job/${mungedProjectName}/job/${mungedBranchName}/job/${inputJobName}/${CORECLR_BUILD}/artifact/tests.checked.zip
3256                 //
3257                 // CoreFX example artifact URLs:
3258                 //
3259                 //  https://ci.dot.net/job/dotnet_coreclr/job/dev_unix_test_workflow/job/jitstress/job/arm64_cross_checked_ubuntu16.04_corefx_baseline_prtest/1/artifact/_/fx/fxruntime.zip
3260                 //  https://ci.dot.net/job/dotnet_coreclr/job/dev_unix_test_workflow/job/jitstress/job/arm64_cross_checked_ubuntu16.04_corefx_baseline_prtest/1/artifact/_/fx/fxtests.zip
3261                 //
3262                 // Note that the source might be in a "jitstress" folder.
3263                 //
3264                 // Use `--progress=dot:giga` to display some progress output, but limit it in the log file.
3265                 //
3266                 // Use `--directory-prefix=_/fx` to specify where to put the corefx files (to match what other platforms do). Use this instead of `-O`.
3267
3268                 shell("echo \"Using wget instead of the Jenkins copy artifacts plug-in to copy artifacts from ${inputCoreCLRBuildName}\"")
3269
3270                 def mungedProjectName = Utilities.getFolderName(project)
3271                 def mungedBranchName = Utilities.getFolderName(branch)
3272
3273                 def doCrossGenComparison = isCrossGenComparisonScenario(scenario)
3274                 def inputCoreCLRBuildScenario = isInnerloopTestScenario(scenario) ? 'innerloop' : 'normal'
3275                 if (isPmiAsmDiffsScenario || doCoreFxTesting || doCrossGenComparison) {
3276                     // These depend on unique builds for each scenario
3277                     inputCoreCLRBuildScenario = scenario
3278                 }
3279                 def sourceJobName = getJobName(configuration, architecture, os, inputCoreCLRBuildScenario, false)
3280                 def inputJobName = Utilities.getFullJobName(sourceJobName, isPR)
3281
3282                 // Need to add the sub-folder if necessary.
3283                 def inputJobPath = "job/${inputJobName}"
3284                 def folderName = getJobFolder(inputCoreCLRBuildScenario)
3285                 if (folderName != '') {
3286                     inputJobPath = "job/${folderName}/job/${inputJobName}"
3287                 }
3288
3289                 def inputUrlRoot = "https://ci.dot.net/job/${mungedProjectName}/job/${mungedBranchName}/${inputJobPath}/\${CORECLR_BUILD}/artifact"
3290
3291                 if (isPmiAsmDiffsScenario) {
3292                     def workspaceRelativeRootLinux = "_/pmi"
3293                     shell("mkdir -p ${workspaceRelativeRootLinux}")
3294                     shell("wget --progress=dot:giga ${inputUrlRoot}/product.${os}.${architecture}.${lowerConfiguration}.zip")
3295                     shell("wget --progress=dot:giga ${inputUrlRoot}/product.baseline.${os}.${architecture}.${lowerConfiguration}.zip")
3296                     shell("wget --progress=dot:giga ${inputUrlRoot}/coreroot.${os}.${architecture}.${lowerConfiguration}.zip")
3297                     shell("wget --progress=dot:giga ${inputUrlRoot}/coreroot.baseline.${os}.${architecture}.${lowerConfiguration}.zip")
3298                 }
3299                 else if (doCoreFxTesting) {
3300                     shell("mkdir -p ${workspaceRelativeFxRootLinux}")
3301                     shell("wget --progress=dot:giga --directory-prefix=${workspaceRelativeFxRootLinux} ${inputUrlRoot}/${workspaceRelativeFxRootLinux}/fxtests.zip")
3302                     shell("wget --progress=dot:giga --directory-prefix=${workspaceRelativeFxRootLinux} ${inputUrlRoot}/${workspaceRelativeFxRootLinux}/fxruntime.zip")
3303                 }
3304                 else {
3305                     def testArtifactsTgzFileName = getTestArtifactsTgzFileName(osGroup, architecture, configuration)
3306                     shell("wget --progress=dot:giga ${inputUrlRoot}/${testArtifactsTgzFileName}")
3307                 }
3308             }
3309
3310             if (architecture == 'x86') {
3311                 shell("mkdir ./bin/CoreFxNative")
3312
3313                 def fxBranch = getFxBranch(branch)
3314                 def corefxFolder = Utilities.getFolderName('dotnet/corefx') + '/' + Utilities.getFolderName(fxBranch)
3315
3316                 copyArtifacts("${corefxFolder}/ubuntu16.04_x86_release") {
3317                     includePatterns('artifacts/bin/build.tar.gz')
3318                     targetDirectory('bin/CoreFxNative')
3319                     buildSelector {
3320                         latestSuccessful(true)
3321                     }
3322                 }
3323
3324                 shell("mkdir ./bin/CoreFxBinDir")
3325                 shell("tar -xf ./bin/CoreFxNative/artifacts/bin/build.tar.gz -C ./bin/CoreFxBinDir")
3326             }
3327
3328             if (isPmiAsmDiffsScenario) {
3329                 // TODO: add back "-q" when we know it works
3330                 shell("unzip -o ./product.${os}.${architecture}.${lowerConfiguration}.zip || exit 0")
3331                 shell("unzip -o ./product.baseline.${os}.${architecture}.${lowerConfiguration}.zip || exit 0")
3332                 shell("unzip -o ./coreroot.${os}.${architecture}.${lowerConfiguration}.zip || exit 0")
3333                 shell("unzip -o ./coreroot.baseline.${os}.${architecture}.${lowerConfiguration}.zip || exit 0")
3334             }
3335             // CoreFX testing downloads the CoreFX tests, not the coreclr tests. Also, unzip the built CoreFX layout/runtime directories.
3336             else if (doCoreFxTesting) {
3337                 shell("unzip -q -o ${workspaceRelativeFxRootLinux}/fxtests.zip || exit 0")
3338                 shell("unzip -q -o ${workspaceRelativeFxRootLinux}/fxruntime.zip || exit 0")
3339             }
3340             else {
3341                 def testArtifactsTgzFileName = getTestArtifactsTgzFileName(osGroup, architecture, configuration)
3342                 shell("tar -xzf ./${testArtifactsTgzFileName} || exit 0") // extracts to ./bin/tests/${osGroup}.${architecture}.${configuration}
3343             }
3344
3345             // Execute the tests
3346             def runDocker = isNeedDocker(architecture, os, false)
3347             def dockerPrefix = ""
3348             def dockerCmd = ""
3349             if (runDocker) {
3350                 def dockerImage = getDockerImageName(architecture, os, false)
3351                 dockerPrefix = "docker run -i --rm -v \${WORKSPACE}:\${WORKSPACE} -w \${WORKSPACE} "
3352                 dockerCmd = dockerPrefix + "${dockerImage} "
3353             }
3354
3355             // If we are running a stress mode, we'll set those variables first.
3356             // For CoreFX, the stress variables are already built into the CoreFX test build per-test wrappers.
3357             if (!doCoreFxTesting && isJitStressScenario(scenario)) {
3358                 def scriptFileName = "\${WORKSPACE}/set_stress_test_env.sh"
3359                 def envScriptCmds = envScriptCreate(os, scriptFileName)
3360                 envScriptCmds += envScriptSetStressModeVariables(os, Constants.jitStressModeScenarios[scenario], scriptFileName)
3361                 envScriptCmds += envScriptFinalize(os, scriptFileName)
3362                 shell("${envScriptCmds}")
3363                 testOpts += " --test-env=${scriptFileName}"
3364             }
3365
3366             // setup-stress-dependencies.sh, invoked by runtest.sh to download the coredistools package, depends on the "dotnet"
3367             // tool downloaded by the "init-tools.sh" script. However, it only invokes setup-stress-dependencies.sh for x64. The
3368             // coredistools package is used by GCStress on x86 and x64 to disassemble code to determine instruction boundaries.
3369             // On arm/arm64, it is not required as determining instruction boundaries is trivial.
3370             if (isGCStressRelatedTesting(scenario)) {
3371                 if (architecture == 'x64') {
3372                     shell('./init-tools.sh')
3373                 }
3374             }
3375
3376             if (isPmiAsmDiffsScenario) {
3377                 shell("""\
3378 python -u \${WORKSPACE}/tests/scripts/run-pmi-diffs.py -arch ${architecture} -ci_arch ${architecture} -build_type ${configuration} --skip_baseline_build""")
3379
3380                 shell("zip -r dasm.${os}.${architecture}.${configuration}.zip ./_/pmi/asm")
3381             }
3382             else if (doCoreFxTesting) {
3383                 shell("""\
3384 \${WORKSPACE}/tests/scripts/run-corefx-tests.sh --test-exclude-file \${WORKSPACE}/tests/${architecture}/corefx_linux_test_exclusions.txt --runtime \${WORKSPACE}/${workspaceRelativeFxRootLinux}/artifacts/bin/testhost/netcoreapp-Linux-Release-${architecture} --arch ${architecture} --corefx-tests \${WORKSPACE}/${workspaceRelativeFxRootLinux}/artifacts/bin --configurationGroup Release""")
3385             }
3386             else {
3387                 def runScript = "${dockerCmd}./tests/runtest.sh"
3388
3389                 shell("""\
3390 ${runScript} \\
3391     ${lowerConfiguration} \\
3392     --testRootDir=\"\${WORKSPACE}/bin/tests/${osGroup}.${architecture}.${configuration}\" \\
3393     --coreOverlayDir=\"\${WORKSPACE}/bin/tests/${osGroup}.${architecture}.${configuration}/Tests/Core_Root\" \\
3394     --limitedDumpGeneration ${testOpts}""")
3395             }
3396
3397             if (isGcReliabilityFramework(scenario)) {
3398                 // runtest.sh doesn't actually execute the reliability framework - do it here.
3399                 if (useServerGC) {
3400                     if (runDocker) {
3401                         dockerCmd = dockerPrefix + "-e COMPlus_gcServer=1 ${dockerImage} "
3402                     }
3403                     else {
3404                         shell("export COMPlus_gcServer=1")
3405                     }
3406                 }
3407
3408                 shell("${dockerCmd}./tests/scripts/run-gc-reliability-framework.sh ${architecture} ${configuration}")
3409             }
3410         } // steps
3411     } // job
3412
3413     // Experimental: If on Ubuntu 14.04, then attempt to pull in crash dump links
3414     if (os in ['Ubuntu']) {
3415         SummaryBuilder summaries = new SummaryBuilder()
3416         summaries.addLinksSummaryFromFile('Crash dumps from this run:', 'dumplings.txt')
3417         summaries.emit(newJob)
3418     }
3419
3420     if (isPmiAsmDiffsScenario) {
3421         // Archive the asm
3422         Utilities.addArchival(newJob, "dasm.${os}.${architecture}.${configuration}.zip")
3423     }
3424     else if (doCoreFxTesting) {
3425         Utilities.addArchival(newJob, "${workspaceRelativeFxRootLinux}/artifacts/bin/**/testResults.xml")
3426         if ((os == "Ubuntu") && (architecture == 'arm')) {
3427             // We have a problem with the xunit plug-in, where it is consistently failing on Ubuntu arm32 test result uploading with this error:
3428             //
3429             //   [xUnit] [ERROR] - The plugin hasn't been performed correctly: remote file operation failed: /ssd/j/workspace/dotnet_coreclr/master/jitstress/arm_cross_checked_ubuntu_corefx_baseline_tst at hudson.remoting.Channel@3697f46d:JNLP4-connect connection from 131.107.159.149/131.107.159.149:58529: java.io.IOException: Remote call on JNLP4-connect connection from 131.107.159.149/131.107.159.149:58529 failed
3430             //
3431             // We haven't been able to identify the reason. So, do not add xunit parsing of the test data in this scenario.
3432             // This is tracked by: https://github.com/dotnet/coreclr/issues/19447.
3433         }
3434         else {
3435             Utilities.addXUnitDotNETResults(newJob, "${workspaceRelativeFxRootLinux}/artifacts/bin/**/testResults.xml")
3436         }
3437     }
3438     else {
3439         Utilities.addXUnitDotNETResults(newJob, '**/coreclrtests.xml')
3440     }
3441
3442     return newJob
3443 }
3444
3445 def static CreateNonWindowsCrossGenComparisonTestJob(def dslFactory, def project, def architecture, def os, def configuration, def scenario, def isPR, def inputCoreCLRBuildName)
3446 {
3447     assert isCrossGenComparisonScenario(scenario)
3448
3449     def osGroup = getOSGroup(os)
3450     def jobName = getJobName(configuration, architecture, os, scenario, false) + "_tst"
3451
3452     def workspaceRelativeResultsDir = "_"
3453     def workspaceRelativeNativeArchResultDir = "${workspaceRelativeResultsDir}/${osGroup}.${architecture}_${architecture}.${configuration}"
3454
3455     def crossArch = "x64"
3456     def workspaceRelativeCrossArchResultDir = "${workspaceRelativeResultsDir}/${osGroup}.${crossArch}_${architecture}.${configuration}"
3457
3458     def jobFolder = getJobFolder(scenario)
3459     def newJob = dslFactory.job(Utilities.getFullJobName(project, jobName, isPR, jobFolder)) {
3460         parameters {
3461             stringParam('CORECLR_BUILD', '', "Build number to copy CoreCLR ${osGroup} binaries from")
3462         }
3463
3464         def workspaceRelativeArtifactsArchive = "${os}.${architecture}.${configuration}.${scenario}.zip"
3465
3466         steps {
3467             copyArtifacts(inputCoreCLRBuildName) {
3468                 includePatterns("${workspaceRelativeArtifactsArchive}")
3469                 buildSelector {
3470                     buildNumber('${CORECLR_BUILD}')
3471                 }
3472             }
3473
3474             shell("unzip -o ${workspaceRelativeArtifactsArchive} || exit 0")
3475
3476             def workspaceRelativeCoreLib = "bin/Product/${osGroup}.${architecture}.${configuration}/IL/System.Private.CoreLib.dll"
3477             def workspaceRelativeCoreRootDir = "bin/tests/${osGroup}.${architecture}.${configuration}/Tests/Core_Root"
3478             def workspaceRelativeCrossGenComparisonScript = "tests/scripts/crossgen_comparison.py"
3479             def workspaceRelativeCrossGenExecutable = "${workspaceRelativeCoreRootDir}/crossgen"
3480
3481             def crossGenComparisonCmd = "python -u \${WORKSPACE}/${workspaceRelativeCrossGenComparisonScript} "
3482             def crossGenExecutable = "\${WORKSPACE}/${workspaceRelativeCrossGenExecutable}"
3483
3484             shell("mkdir -p ${workspaceRelativeNativeArchResultDir}")
3485             shell("${crossGenComparisonCmd}crossgen_corelib --crossgen ${crossGenExecutable} --il_corelib \${WORKSPACE}/${workspaceRelativeCoreLib} --result_dir \${WORKSPACE}/${workspaceRelativeNativeArchResultDir}")
3486             shell("${crossGenComparisonCmd}crossgen_framework --crossgen ${crossGenExecutable} --core_root \${WORKSPACE}/${workspaceRelativeCoreRootDir} --result_dir \${WORKSPACE}/${workspaceRelativeNativeArchResultDir}")
3487
3488             shell("${crossGenComparisonCmd}compare --base_dir \${WORKSPACE}/${workspaceRelativeNativeArchResultDir} --diff_dir \${WORKSPACE}/${workspaceRelativeCrossArchResultDir}")
3489         } // steps
3490     }  // job
3491
3492     Utilities.addArchival(newJob, "${workspaceRelativeNativeArchResultDir}/**")
3493     Utilities.addArchival(newJob, "${workspaceRelativeCrossArchResultDir}/**")
3494
3495     return newJob
3496 }
3497
3498 // Create a test job that will be used by a flow job.
3499 // Returns the newly created job.
3500 // Note that we don't add tests jobs to the various views, since they are always used by a flow job, which is in the views,
3501 // and we want the views to be the minimal set of "top-level" jobs that represent all work.
3502 def static CreateTestJob(def dslFactory, def project, def branch, def architecture, def os, def configuration, def scenario, def isPR, def inputCoreCLRBuildName)
3503 {
3504     def windowsArmJob = ((os == "Windows_NT") && (architecture in Constants.armWindowsCrossArchitectureList))
3505
3506     def newJob = null
3507     if (windowsArmJob) {
3508         newJob = CreateWindowsArmTestJob(dslFactory, project, architecture, os, configuration, scenario, isPR, inputCoreCLRBuildName)
3509     }
3510     else if (isCrossGenComparisonScenario(scenario)) {
3511         newJob = CreateNonWindowsCrossGenComparisonTestJob(dslFactory, project, architecture, os, configuration, scenario, isPR, inputCoreCLRBuildName)
3512     }
3513     else {
3514         newJob = CreateOtherTestJob(dslFactory, project, branch, architecture, os, configuration, scenario, isPR, inputCoreCLRBuildName)
3515     }
3516
3517     setJobMachineAffinity(architecture, os, false, true, false, newJob) // isBuildJob = false, isTestJob = true, isFlowJob = false
3518
3519     if (scenario == 'jitdiff') {
3520         def osGroup = getOSGroup(os)
3521         Utilities.addArchival(newJob, "bin/tests/${osGroup}.${architecture}.${configuration}/dasm/**")
3522     }
3523
3524     Utilities.standardJobSetup(newJob, project, isPR, "*/${branch}")
3525     setJobTimeout(newJob, isPR, architecture, configuration, scenario, false)
3526
3527     return newJob
3528 }
3529
3530 // Create a flow job to tie together a build job with the given test job.
3531 // Returns the new flow job.
3532 def static CreateFlowJob(def dslFactory, def project, def branch, def architecture, def os, def configuration, def scenario, def isPR, def fullTestJobName, def inputCoreCLRBuildName)
3533 {
3534     // Windows CoreCLR build and Linux CoreCLR build (in parallel) ->
3535     // Linux CoreCLR test
3536     def flowJobName = getJobName(configuration, architecture, os, scenario, false) + "_flow"
3537     def jobFolder = getJobFolder(scenario)
3538
3539     def newFlowJob = dslFactory.buildFlowJob(Utilities.getFullJobName(project, flowJobName, isPR, jobFolder)) {
3540         buildFlow("""\
3541 coreclrBuildJob = build(params, '${inputCoreCLRBuildName}')
3542
3543 // And then build the test build
3544 build(params + [CORECLR_BUILD: coreclrBuildJob.build.number], '${fullTestJobName}')
3545 """)
3546     }
3547     JobReport.Report.addReference(inputCoreCLRBuildName)
3548     JobReport.Report.addReference(fullTestJobName)
3549
3550     addToViews(newFlowJob, true, isPR, architecture, os, configuration, scenario) // isFlowJob = true
3551
3552     setJobMachineAffinity(architecture, os, false, false, true, newFlowJob) // isBuildJob = false, isTestJob = false, isFlowJob = true
3553
3554     Utilities.standardJobSetup(newFlowJob, project, isPR, "*/${branch}")
3555     addTriggers(newFlowJob, branch, isPR, architecture, os, configuration, scenario, true, false) // isFlowJob==true, isWindowsBuildOnlyJob==false
3556
3557     return newFlowJob
3558 }
3559
3560 // Determine if we should generate a flow job for the given parameters.
3561 // Returns true if the job should be generated.
3562 def static shouldGenerateFlowJob(def scenario, def isPR, def architecture, def configuration, def os)
3563 {
3564     // The various "innerloop" jobs are only available as PR triggered.
3565
3566     if (!isPR) {
3567         if (isInnerloopTestScenario(scenario)) {
3568             return false
3569         }
3570
3571         if (scenario == 'corefx_innerloop') {
3572             return false
3573         }
3574     }
3575
3576     // Filter based on OS and architecture.
3577
3578     switch (architecture) {
3579         case 'arm':
3580             if (os != "Ubuntu" && os != "Windows_NT") {
3581                 return false
3582             }
3583             break
3584         case 'arm64':
3585             if (os != "Ubuntu16.04" && os != "Windows_NT") {
3586                 return false
3587             }
3588             break
3589         case 'x86':
3590             if (os != "Ubuntu") {
3591                 return false
3592             }
3593             break
3594         case 'x64':
3595             if (!(os in Constants.crossList)) {
3596                 return false
3597             }
3598             if (os == "Windows_NT") {
3599                 return false
3600             }
3601             break
3602         case 'armem':
3603             // No flow jobs
3604             return false
3605         default:
3606             println("Unknown architecture: ${architecture}")
3607             assert false
3608             break
3609     }
3610
3611     def isNormalOrInnerloop = (scenario == 'innerloop' || scenario == 'normal')
3612
3613     // Filter based on scenario in OS.
3614
3615     if (os == 'Windows_NT') {
3616         assert architecture == 'arm' || architecture == 'arm64'
3617         if (!isArmWindowsScenario(scenario)) {
3618             return false
3619         }
3620         if (isNormalOrInnerloop && (configuration == 'Debug')) {
3621             // The arm32/arm64 Debug configuration for innerloop/normal scenario is a special case: it does a build only, and no test run.
3622             // To do that, it doesn't require a flow job.
3623             return false
3624         }
3625     }
3626     else {
3627         // Non-Windows
3628         if (architecture == 'arm') {
3629             if (!(scenario in Constants.validLinuxArmScenarios)) {
3630                 return false
3631             }
3632         }
3633         else if (architecture == 'arm64') {
3634             if (!(scenario in Constants.validLinuxArm64Scenarios)) {
3635                 return false
3636             }
3637         }
3638         else if (architecture == 'x86') {
3639             // Linux/x86 only want innerloop and default test
3640             if (!isNormalOrInnerloop) {
3641                 return false
3642             }
3643         }
3644         else if (architecture == 'x64') {
3645             // Linux/x64 corefx testing doesn't need a flow job; the "build" job runs run-corefx-tests.py which
3646             // builds and runs the corefx tests. Other Linux/x64 flow jobs are required to get the test
3647             // build from a Windows machine.
3648             if (isCoreFxScenario(scenario)) {
3649                 return false
3650             }
3651         }
3652     }
3653
3654     // For CentOS, we only want Checked/Release builds.
3655     if (os == 'CentOS7.1') {
3656         if (configuration != 'Checked' && configuration != 'Release') {
3657             return false
3658         }
3659         if (!isNormalOrInnerloop && !isR2RScenario(scenario)) {
3660             return false
3661         }
3662     }
3663
3664     // For RedHat and Debian, we only do Release builds.
3665     else if (os == 'RHEL7.2' || os == 'Debian8.4') {
3666         if (configuration != 'Release') {
3667             return false
3668         }
3669         if (!isNormalOrInnerloop) {
3670             return false
3671         }
3672     }
3673
3674     // Next, filter based on scenario.
3675
3676     if (isJitStressScenario(scenario)) {
3677         if (configuration != 'Checked') {
3678             return false
3679         }
3680     }
3681     else if (isR2RBaselineScenario(scenario)) {
3682         if (configuration != 'Checked' && configuration != 'Release') {
3683             return false
3684         }
3685     }
3686     else if (isR2RStressScenario(scenario)) {
3687         if (configuration != 'Checked') {
3688             return false
3689         }
3690     }
3691     else if (isCrossGenComparisonScenario(scenario)) {
3692         return shouldGenerateCrossGenComparisonJob(os, architecture, configuration, scenario)
3693     }
3694     else {
3695         // Skip scenarios
3696         switch (scenario) {
3697             case 'ilrt':
3698             case 'longgc':
3699             case 'gcsimulator':
3700                 // Long GC tests take a long time on non-Release builds
3701                 // ilrt is also Release only
3702                 if (configuration != 'Release') {
3703                     return false
3704                 }
3705                 break
3706
3707             case 'jitdiff':
3708                 if (configuration != 'Checked') {
3709                     return false
3710                 }
3711                 break
3712
3713             case 'gc_reliability_framework':
3714             case 'standalone_gc':
3715                 if (configuration != 'Release' && configuration != 'Checked') {
3716                     return false
3717                 }
3718                 break
3719
3720             case 'formatting':
3721                 return false
3722
3723             case 'illink':
3724                 if (os != 'Windows_NT' && os != 'Ubuntu') {
3725                     return false
3726                 }
3727                 break
3728
3729             case 'normal':
3730                 // Nothing skipped
3731                 break
3732
3733             case 'innerloop':
3734                 if (!isValidPrTriggeredInnerLoopJob(os, architecture, configuration, false)) {
3735                     return false
3736                 }
3737                 break
3738
3739             case 'pmi_asm_diffs':
3740                 if (configuration != 'Checked') {
3741                     return false
3742                 }
3743                 // No need for flow job except for Linux arm/arm64
3744                 if ((os != 'Windows_NT') && (architecture != 'arm') && (architecture != 'arm64')) {
3745                     return false
3746                 }
3747                 break
3748
3749             case 'corefx_innerloop':
3750                 // No flow job needed
3751                 return false
3752
3753             default:
3754                 println("Unknown scenario: ${scenario}")
3755                 assert false
3756                 break
3757         }
3758     }
3759
3760     // The job was not filtered out, so we should generate it!
3761     return true
3762 }
3763
3764 // Create jobs requiring flow jobs. This includes x64 non-Windows, arm/arm64 Ubuntu, and arm/arm64 Windows.
3765 Constants.allScenarios.each { scenario ->
3766     [true, false].each { isPR ->
3767         Constants.architectureList.each { architecture ->
3768             Constants.configurationList.each { configuration ->
3769                 Constants.osList.each { os ->
3770
3771                     if (!shouldGenerateFlowJob(scenario, isPR, architecture, configuration, os)) {
3772                         return
3773                     }
3774
3775                     def windowsArmJob = ((os == "Windows_NT") && (architecture in Constants.armWindowsCrossArchitectureList))
3776                     def doCoreFxTesting = isCoreFxScenario(scenario)
3777                     def doCrossGenComparison = isCrossGenComparisonScenario(scenario)
3778                     def isPmiAsmDiffsScenario = (scenario == 'pmi_asm_diffs')
3779
3780                     // Figure out the job name of the CoreCLR build the test will depend on.
3781
3782                     def inputCoreCLRBuildScenario = isInnerloopTestScenario(scenario) ? 'innerloop' : 'normal'
3783                     def inputCoreCLRBuildIsBuildOnly = false
3784                     if (doCoreFxTesting || isPmiAsmDiffsScenario) {
3785                         // Every CoreFx test depends on its own unique build.
3786                         inputCoreCLRBuildScenario = scenario
3787                         if (windowsArmJob) {
3788                             // Only Windows ARM corefx jobs use "build only" jobs. Others, such as Ubuntu ARM corefx, use "regular" jobs.
3789                             inputCoreCLRBuildIsBuildOnly = true
3790                         }
3791                     }
3792                     else if (doCrossGenComparison) {
3793                         inputCoreCLRBuildScenario = scenario
3794                     }
3795
3796                     def inputCoreCLRFolderName = getJobFolder(inputCoreCLRBuildScenario)
3797                     def inputCoreCLRBuildName = projectFolder + '/' +
3798                         Utilities.getFullJobName(project, getJobName(configuration, architecture, os, inputCoreCLRBuildScenario, inputCoreCLRBuildIsBuildOnly), isPR, inputCoreCLRFolderName)
3799
3800                     // =============================================================================================
3801                     // Create the test job
3802                     // =============================================================================================
3803
3804                     def testJob = CreateTestJob(this, project, branch, architecture, os, configuration, scenario, isPR, inputCoreCLRBuildName)
3805
3806                     // =============================================================================================
3807                     // Create a build flow to join together the build and tests required to run this test.
3808                     // =============================================================================================
3809
3810                     if (os == 'RHEL7.2' || os == 'Debian8.4') {
3811                         // Do not create the flow job for RHEL jobs.
3812                         return
3813                     }
3814
3815                     def fullTestJobName = projectFolder + '/' + testJob.name
3816                     def flowJob = CreateFlowJob(this, project, branch, architecture, os, configuration, scenario, isPR, fullTestJobName, inputCoreCLRBuildName)
3817
3818                 } // os
3819             } // configuration
3820         } // architecture
3821     } // isPR
3822 } // scenario
3823
3824 JobReport.Report.generateJobReport(out)
3825
3826 // Make the call to generate the help job
3827 Utilities.createHelperJob(this, project, branch,
3828     "Welcome to the ${project} Repository",  // This is prepended to the help message
3829     "Have a nice day!")  // This is appended to the help message.  You might put known issues here.
3830
3831 Utilities.addCROSSCheck(this, project, branch)